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"
}
}
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.