我怎样才能合并两个JObject?

时间:2014-01-16 11:20:15

标签: c# .net json json.net

我有第一个json:

{
    "data": [{
      "id": "id1",
      "field": "field1"
    }],
    "paging": {
        "prev": "link1",
    }
}

和第二个:

{
    "data": [{
      "id": "id2",
      "field": "field2"
    }],
    "paging": {
        "prev": "link2",
    }
}

我希望合并/联合两个Data数组,例如:

{
    "data": [{
      "id": "id1",
      "field": "field1"
    },
    {
      "id": "id2",
      "field": "field2"
    }]  
}

(我现在不关心paging)。

我怎样才能快速轻松地完成?这是我的尝试:

var final = JsonConvert.SerializeObject(new { data = json1["data"].Union(json2["data"]) }, Newtonsoft.Json.Formatting.Indented).ToString();

但引发了异常:'Newtonsoft.Json.Linq.JArray' does not contains a definition of 'Union'

4 个答案:

答案 0 :(得分:34)

Newtonsoft.Json现在支持合并对象:
http://antix.co.uk/Blog/Merging-objects-using-JSON.NET

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

(用脑编译器检查;))

答案 1 :(得分:7)

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

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

foreach(JObject innerData in dataofJson2) 
{
    dataOfJson1.Add(innerData);
}

答案 2 :(得分:3)

可能的解决方案可能是:

class Container
{
    public List<IdField> data{get;set;}
}

class IdField
{
    public string id{get;set;}
    public string field{get;set;}
}


string s1 = "{ \"data\": [{ \"id\": \"id1\", \"field\": \"field1\" }], \"paging\": { \"prev\": \"link1\", } }";
string s2 = "{ \"data\": [{ \"id\": \"id2\", \"field\": \"field2\" }], \"paging\": { \"prev\": \"link2\", } }";

var d1 = JsonConvert.DeserializeObject<Container>(s1);
var d2 = JsonConvert.DeserializeObject<Container>(s2);

d1.data.AddRange(d2.data);

var result = JsonConvert.SerializeObject(d1);

答案 3 :(得分:2)

对于那些(像我一样)不能使用新的JSON.net库的人。 我使用的是以下方法。

public static JObject mergeJsonObjects(List<JObject> objects) {

    JObject json = new JObject();
    foreach(JObject JSONObject in objects) {
        foreach(var property in JSONObject) {
            string name = property.Key;
            JToken value = property.Value;

            json.Add(property.Key, property.Value);
        }
    }

    return json;
}

该方法获取JObject的列表并返回单个JObject,simpel和effective。