json 如何合并两个JObject?[副本]

bybem2ql  于 2023-10-21  发布在  其他
关注(0)|答案(4)|浏览(112)
    • 此问题已在此处有答案**:

Merge two Json.NET arrays by concatenating contained elements(3个答案)
7年前关闭。
我有一个第一个json:

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

以及第二个:

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

我想合并/联合两个数据数组,例如:

{
    "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'

wwodge7n

wwodge7n1#

Newtonsoft.json现在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));

(用brain-compiler检查;)的情况)

v2g6jxz6

v2g6jxz62#

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

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

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

aiqt4smr3#

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

public static JObject mergeJsonObjects(List<JObject> objects) {
        
    JObject json = new JObject();
    foreach(JObject JSONObject in objects) {
        foreach(var property in JSONObject) {
            json.Add(property.Key, property.Value);
        }
    }

    return json;
}

该方法接受一个JObject列表并返回单个JObject,简单而有效。

niwlg2el

niwlg2el4#

一种可能的解决办法是:

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

相关问题