I have a first json:
{
"data": [{
"id": "id1",
"field": "field1"
}],
"paging": {
"prev": "link1",
}
}
and a second one:
{
"data": [{
"id": "id2",
"field": "field2"
}],
"paging": {
"prev": "link2",
}
}
and I want to merge/union the two Data array, such as:
{
"data": [{
"id": "id1",
"field": "field1"
},
{
"id": "id2",
"field": "field2"
}]
}
(I don't care about about paging
right now).
How can I do it quick and easy? This is my try:
var final = JsonConvert.SerializeObject(new { data = json1["data"].Union(json2["data"]) }, Newtonsoft.Json.Formatting.Indented).ToString();
but an Exception is raised: 'Newtonsoft.Json.Linq.JArray' does not contains a definition of 'Union'
To perform the merge, we simply need to call the Merge method on our result JObject, passing as input one of the parsed JObjects. Then, we will call the method again, passing as input the second parsed JObject. result. Merge(jObject1);
JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.
You can use JObject. Merge to merge two different objects into one: JObject o1 = JObject. Parse(@"{ 'FirstName': 'John', 'LastName': 'Smith', 'Enabled': false, 'Roles': [ 'User' ] }"); JObject o2 = JObject.
Newtonsoft.Json now supports merging objects (old link):
var dataObject1 = JObject.Parse(@"{
""data"": [{
""id"": ""id1"",
""field"": ""field1""
}],
""paging"": {
""prev"": ""link1"",
}
}");
var dataObject2 = JObject.Parse(@"{
""data"": [{
""id"": ""id2"",
""field"": ""field2""
}],
""paging"": {
""prev"": ""link2"",
}
}");
var mergeSettings = new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
};
// method 1
(dataObject1.SelectToken("data") as JArray).Merge(dataObject2.SelectToken("data"), mergeSettings);
// method 2
//dataObject1.Merge(dataObject2, mergeSettings);
var mergedArray = dataObject1.SelectToken("data") as JArray;
Console.WriteLine(mergedArray.ToString(Formatting.None));
(checked with brain-compiler ;) )
JArray dataOfJson1=json1.SelectToken("data");
JArray dataofJson2=json2.SelectToken("data");
foreach(JObject innerData in dataofJson2)
{
dataOfJson1.Add(innerData);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With