我正在处理合并json数组的一些问题。要合并的原始数组看起来类似于以下内容:
{
"ads":[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
}
]
}
{
"ads": [
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
}
我的合并结果看起来类似于此:
{
"ads:[
[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
}
],
[
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
]
}
我想把它简化为:
{
"ads:[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
},
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
}
目前用于尝试合并两者的代码是:
// Combine all ads within formattedContent into one single JOBject.
JToken token = null;
JArray jarray = new JArray();
List<JToken> jtokens = new List<JToken>();
foreach (JObject jobject in formattedContent)
{
token = JToken.Parse(jobject.SelectToken("ads").ToString());
jarray.Add(token);
}
但是,当最终产品需要在一个数组下的"ads"标记中产生所有ads时,我就陷入了双重嵌套数组的困境。请注意,上面代码中的formattedContent是一个List<JObject>
。如有任何关于合并json数组的帮助,我们将不胜感激。在将令牌添加到JArray之前,尝试将其添加到字符串中会导致回车和转义字符被添加
您要做的是将token.Children()
而不是token
添加到jarray
(即添加token
的内容而不是添加token
本身):
var jarray = new JArray();
foreach (var jobject in formattedContent)
{
var token = jobject.SelectToken("ads") as JArray;
if (token != null)
jarray.Add(token.Children());
}
顺便说一句,在根对象上使用JContainer.Merge()
也可以达到同样的效果,设置为JsonMergeSettings.MergeArrayHandling = MergeArrayHandling.Concat
:
var merged = new JObject();
var settings = new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Concat,
};
foreach (var jobject in formattedContent)
{
merged.Merge(jobject, settings);
}