简体   繁体   English

合并所有嵌套的Json对象

[英]Merge all Nested Json Objects

I have got a following json. 我有以下json。 I want to merge all nested json objects into one. 我想将所有嵌套的json对象合并为一个。

    [
      {
        "2": "a",
        "3": "a"
      },
      {
        "2": "f",
        "3": "a",
        "4": "p"
      },
      {
        "2": "n",
        "3": "o",
        "4": "t"
      }
    ]

so, the output of the above json would be 因此,上述json的输出为

[  
   {  
      "0":"a",
      "1":"a",
      "2":"f",
      "3":"a",
      "4":"p",
      "5":"n",
      "6":"o",
      "7":"t"
   }
]

I tried to parse the json array and then add all values and append it to another array. 我试图解析json数组,然后添加所有值并将其附加到另一个数组。 However, is there any other elegant solution to merge all nested json objects to one? 但是,还有其他优雅的解决方案可以将所有嵌套的json对象合并为一个吗?

Given that you need to change indices, manual merging is unavoidable. 鉴于您需要更改索引,因此手动合并是不可避免的。

Eg SelectMany from Linq could be used for merging as: 例如,来自Linq的SelectMany可用于合并:

var input = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(@"
[
  {
    ""2"": ""a"",
    ""3"": ""a""
  },
  {
    ""2"": ""f"",
    ""3"": ""a"",
    ""4"": ""p""
  },
  {
    ""2"": ""n"",
    ""3"": ""o"",
    ""4"": ""t""
  }
]");

var result = input
    .SelectMany(d => d.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
    .Select((value, index) => new {index, value})
    .ToDictionary(iv => iv.index, iv => iv.value);

 var jsonResult = JsonConvert.SerializeObject(result);

You can use the tool called json .net Check the following code : 您可以使用名为json .net的工具检查以下代码:

var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(sw, model);
        JObject o1 = JObject.Parse(@"{
         'FirstName': 'John',
         'LastName': 'Smith',
         'Enabled': false,
         'Roles': [ 'User' ]
          }");
        JObject o2 = JObject.Parse(@"{
         'Enabled': true,
         'Roles': [ 'User', 'Admin' ]
          }");

        o1.Merge(o2, new JsonMergeSettings
        {
            // union array values together to avoid duplicates
            MergeArrayHandling = MergeArrayHandling.Union
        });

        string json = o1.ToString();
        // {
        //   "FirstName": "John",
        //   "LastName": "Smith",
        //   "Enabled": true,
        //   "Roles": [
        //     "User",
        //     "Admin"
        //   ]
        // }

Please Check Link : https://www.newtonsoft.com/json/help/html/MergeJson.htm 请检查链接: https : //www.newtonsoft.com/json/help/html/MergeJson.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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