0

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.

3
  • 1
    what if you create a json with all the elements again. Commented Mar 17, 2015 at 7:02
  • 1
    What if you create a json with all the elements again ? Also no gender in first one,then how it gets updated.! Commented Mar 17, 2015 at 7:03
  • @utility please check the updated question. I need something like above explained. but it is not working, raised some exception can't add same property to object Commented Mar 17, 2015 at 7:06

1 Answer 1

10

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.

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.