Raghu Raghu - 3 years ago 109
C# Question

Using JSON.NET and C# , Could we able to convert json as shown below?

Input json :

{
"name" : "objname",
"abc" : 1,
"def" : 2
}


Desired Output JSON

{
"objname" :
{
"abc" : 1,
"def" : 2
}
}


I Tried, somthing like this, but i feel, its not the correct way.

var obj = JsonConvert.DeserializeObject(json);

StringBuilder sb = new StringBuilder();
sb.Append(" { ");
sb.AppendLine(obj.Name);
sb.AppendLine(" : {");
sb.AppendLine(GetMemberName(() => obj.abc) + ":" + obj.abc + ",");
sb.AppendLine(GetMemberName(() => obj.def) + ":" + obj.abc);
sb.AppendLine(" : }");

public class Obj
{
public string Name { get;set;}
public string abc { get; set; }
public string def { get; set; }
}

Answer Source

The first step is deserializing. You can just go to a dictionary:

Dictionary<string, string> dict = 
    JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Then, to get it back, you probably need to use a dictionary as well. You cannot use a predefined (even compiler generated) class, since you don't know the property name.

String name = (string)dict["name"];
// remove name from dictionary
dict.Remove(name);
var output = 
   new Dictionary<string,object>() {{name, dict}};

Then, save it back out:

string json = JsonConvert.SerializeObject(output);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download