简体   繁体   中英

Convert one JSON structure to another using Json.Net

Input JSON:

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

Desired output JSON:

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

I tried as shown below, but I feel it's not the correct way.

// This is the class object
public class Obj
{
    public string Name { get;set;}
    public string abc { get; set; }
    public string def { get; set; }
}         

var obj = JsonConvert.DeserializeObject<Obj>(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(" :  }");

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM