Reputation: 1755
I have a json object something like
{ "name" : "sai", "age" : 22, "salary" : 25000}
I want to update the json object by
{ "name" : "sai", "age" : 23, "Gender" : "male"}
Then I want result something like
{ "name" : "sai", "age" : 23, "salary" : 25000, "Gender" : "male"}
I tried something like
foreach (var item in actualJson)
{
bool isFound = false;
foreach (var newItem in newJson)
{
if(item == newItem) // always returns false, anything wrong with this?
{
isFound = true;
break;
}
}
if(!isFound)
{
// add to json
}
}
I am not getting any Idea to solve this?
Any help/guidance would be greatly appreciated.
Upvotes: 0
Views: 13271
Reputation: 1067
With Json.NET you can do something like this:
var json1 = "{ \"name\" : \"sai\", \"age\" : 22, \"salary\" : 25000}";
var json2 = "{ \"name\" : \"sai\", \"age\" : 23, \"Gender\" : \"male\"}";
var object1 = JObject.Parse(json1);
var object2 = JObject.Parse(json2);
foreach (var prop in object2.Properties())
{
var targetProperty = object1.Property(prop.Name);
if (targetProperty == null)
{
object1.Add(prop.Name, prop.Value);
}
else
{
targetProperty.Value = prop.Value;
}
}
var result = object1.ToString(Formatting.None);
This will either add a property of json2 to json1 if it doesn't exist or it will update the value if it exists.
Upvotes: 10