gpt4 book ai didi

c# - 如何使用 NewtonSoft 在 C# 中从另一个 json 替换 json?

转载 作者:行者123 更新时间:2023-12-04 15:19:24 26 4
gpt4 key购买 nike

我有两个 JSON 对象 -

json1 = {
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "test1",
"arrayProp1": [1, 2, 3],
"arrayProp2": [{
"prop1": "value1",
"prop2": "value2"
},
{
"prop1": "2_value1",
"prop2": "2_value2"
}
]
}
}

json2 = {
"payload": {
"code": "newCode",
"arrayProp1": [3,4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}
]
}
}

如果我使用内置合并 (json1.Merge(json2)),得到的结果是 -

result : {
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "newCode",
"arrayProp1": [1, 2, 3, 3, 4],
"arrayProp2": [{
"prop1": "value1",
"prop2": "value2"
},
{
"prop1": "newValue1",
"prop2": "newValue2"
},
{
"prop1": "2_value1",
"prop2": "2_value2"
}
]
}
}

预期结果-

{
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "newCode",
"arrayProp1": [3, 4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}]
}
}

我想根据 json2 中提供的值替换 json1 的父属性值。

我尝试编写一个函数,这是我的当前版本 -

string Merge(string req1, string req2) {
try
{
JObject json1 = JObject.Parse(req1);
JObject json2 = JObject.Parse(req2);

foreach (var a in json2.DescendantsAndSelf())
{
if (a is JObject obj)
{
foreach (var prop in obj.Properties())
{
if(json1.SelectTokens(prop.Path).Any())
{
json1[prop.Path] = prop.Value;
}
}
}

}
req1 = json1.ToString();
}
catch(Exception ex)
{
//do nothing
}
return req1; }

这里有2个问题-

  1. “payload”被识别为属性,json1 被 json2 完全替换,因此我失去了它的一些属性。
  2. 被替换后,当循环继续运行时,说要更新属性'code',则属性路径为payload.code,所以在json1[prop.path] = prop.Value这一行,而不是更新有效负载中的现有代码,它创建一个名为 payload.code 的新属性,值为“newcode”

上面代码的最终结果是——

{
"payload": {
"code": "newCode",
"arrayProp1": [3, 4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}],
"payload.code": "newCode",
"payload.arrayProp1": [3, 4],
"payload.arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}],
"payload.arrayProp1[0].prop1": "newValue1",
"payload.arrayProp1[0].prop2": "newValue2"
}
}

有人可以帮我解决这个问题吗?

最佳答案

您的要求是,在使用 JContainer.Merge() 合并两个 JSON 对象时,数组内容被替换而不是连接起来.您可以通过 JsonMergeSettings.MergeArrayHandling 实现此目的设置,具有以下 values :

Concat   0   Concatenate arrays.
Union 1 Union arrays, skipping items that already exist.
Replace 2 Replace all array items.
Merge 3 Merge array items together, matched by index.

具体来说,MergeArrayHandling.Replace 将按要求工作:

json1.Merge(json2, new JsonMergeSettings 
{
MergeArrayHandling = MergeArrayHandling.Replace
});

演示 fiddle here .

关于c# - 如何使用 NewtonSoft 在 C# 中从另一个 json 替换 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63674113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com