简体   繁体   English

如何使用 JSON.NET 合并两个 json 对象

[英]How to merge two json objects using JSON.NET

I have below requirement, where I need to merge two Json objects using JSON.NET.我有以下要求,我需要使用 JSON.NET 合并两个 Json 对象。 Below is the sample code下面是示例代码

    string jsonText = @"
    {
      ""food"": {
        ""fruit"": {
          ""apple"": {
            ""colour"": ""red"",
            ""size"": ""small""
          },
          ""orange"": {
            ""colour"": ""orange"",
            ""size"": ""large""
          }
        }
      }
    }";

    var foodJsonObj = JObject.Parse(jsonText);
    var foodJsonToken = foodJsonObj.SelectToken("food.fruit") as JObject;
    var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}, ""simpletype"":""simplevalue"", ""orange"":{ ""newprop"": ""newpropvalue"" }  }");
    var bananaToken = bananaJson as JObject;

    foreach (var token1 in bananaToken)
    {
        **var existingTokens = foodJsonToken.Children();
        foreach (var item in existingTokens)
        {
            var existingObject = item as JObject;

        }
        if (existingTokens.Contains(token1.Key))
        {
            foodJsonToken.Merge(token1, new JsonMergeSettings
            {
                MergeArrayHandling = MergeArrayHandling.Union
            });
        }**
        else
        {
            foodJsonToken.Add(token1.Key, token1.Value);
        }
    }

    json = foodJsonToken.ToString();

In the above example, I want to merge banana json into food json在上面的例子中,我想将香蕉 json 合并到食物 json 中

above code is working without hightlighted code, if the bananajson does not have “orange” property which already in food json如果bananajson没有已经在food json中的“orange”属性,则上面的代码在没有高亮代码的情况下工作

if both have similar set of properties, above code is not working.如果两者都具有相似的属性集,则上述代码不起作用。 Is there any way to using linq to find existing element, if that exists, I want to merge the json else it going to update source with new properties.有什么方法可以使用 linq 查找现有元素,如果存在,我想合并 json,否则它将使用新属性更新源。

Regards, Amar问候, 阿马尔

If the structure of you main json is always the same you can create two classes:如果主 json 的结构始终相同,则可以创建两个类:

a) Main class Food with collections of fruits b) Fruit class with fields: colour and size a) 带有水果集合的主类食品 b) 带有字段的水果类:颜色和大小

You can easily add/remove any fruit from the Food class collection.您可以轻松地从 Food 类集合中添加/删除任何水果。 You can serialize/deserialize Food or Fruit class using NewtonSoft library.您可以使用 NewtonSoft 库序列化/反序列化 Food 或 Fruit 类。

The whole code should look like:整个代码应该如下所示:

[DataContract]  
class Food
{  
    [DataMember]  
    public ArrayList<Fruit> Fruit { get; set; }  
}

[DataContract]
class Fruit
{  
    [DataMember]  
    public string Name { get; set; }  

    [DataMember]  
    public string Colour { get; set; }  

    [DataMember]  
    public string Size{ get; set; }  
}

Example usage:用法示例:

var sampleFoodInstanc = new Food();
sampleFoodInstance.Fruit.Add( new Fruit() { Name: "Apple", Colour: "Red", Size: "Big" } );

// serialize process
var sz = JsonConvert.SerializeObject( sampleFoodInstance );

// deserialize process
JsonConvert.DeserializeObject<Food>( sz );

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

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