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

1
  • 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 }); Commented Sep 1, 2017 at 3:54

1 Answer 1

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.