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