1

I have below requirement, where I need to merge two Json objects using JSON.NET. 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

above code is working without hightlighted code, if the bananajson does not have “orange” property which already in food json

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.

Regards, Amar

Amar Ta
  • 33
  • 2
  • 6
  • why don't you just use it instead of looping. in this case you will have to wrap the banana token with ""fruit"": {} before merging: foodJsonToken.Merge(bananaToken, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); – Rakib Sep 01 '17 at 03:54

1 Answers1

1

If the structure of you main json is always the same you can create two classes:

a) Main class Food with collections of fruits b) Fruit class with fields: colour and size

You can easily add/remove any fruit from the Food class collection. You can serialize/deserialize Food or Fruit class using NewtonSoft library.

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