Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two JObject? [duplicate]

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'

like image 620
markzzz Avatar asked Jan 16 '14 11:01

markzzz


People also ask

How to merge two JObject?

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);

How do I combine two Jsons?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.

How to combine two JSON in c#?

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.


2 Answers

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 ;) )

like image 50
David Rettenbacher Avatar answered Sep 19 '22 18:09

David Rettenbacher


JArray dataOfJson1=json1.SelectToken("data");

JArray dataofJson2=json2.SelectToken("data");

foreach(JObject innerData in dataofJson2) 
{
    dataOfJson1.Add(innerData);
}
like image 36
Dibu Avatar answered Sep 21 '22 18:09

Dibu