Search code examples
c#jsonjson.net

Joining 2 json string using c# or jobject or newtonsoft


Hi given I have 2 json files and I would like to join them

{
    "PropertyOne": "PropOne",
    "PropertyTwo": "PropTwo",
    "PropertyThree": "PropThree"
}

and

{
    "MyObject": {
        "PropertyOne": "PropOne",
        "PropertyTwo": "PropTwo",
        "PropertyThree": "PropThree"
    }
}

How can I join them get the below outcome and be a valid json?

{
"PropertyOne": "PropOne",
"PropertyTwo": "PropTwo",
"PropertyThree": "PropThree",
"MyObject": {
    "PropertyOne": "PropOne",
    "PropertyTwo": "PropTwo",
  "PropertyThree": "PropThree"
}

}


Solution

  • I would suggest using Newtonsoft. It is available via Nuget for easy install.

    string json1 = @"{'PropertyOne': 'PropOne','PropertyTwo': 'PropTwo','PropertyThree': 'PropThree'}";
    string json2 = @"{'MyObject': {'PropertyOne': 'PropOne','PropertyTwo': 'PropTwo','PropertyThree': 'PropThree'}}";
    
    JObject j1 = JObject.Parse(json1);
    JObject j2 = JObject.Parse(json2);
    
    j1.Merge(j2, new JsonMergeSettings {
        MergeArrayHandling = MergeArrayHandling.Union
    });
    

    Here you would create your two JSON string objects, parse both of them using JObject. Then using the merge method you can let Newtonsoft take care of it behind the scenes. The resulting j1 object has your desired output.