如何在Newtonsoft JSON.Net中合并来自两个JObjects的两个数组? [英] How do I combine two arrays from two JObjects in Newtonsoft JSON.Net?
问题描述
我有两个在其上运行过JObject.FromObject()
的类似JSON对象.
I have two similar JSON objects that I have run JObject.FromObject()
on.
每个对象中都有一个带有其他对象数组的属性,如下所示:
In each object there is a property with an array of other objects, like so:
{
"Title": "Alpha",
"data": [
{
"Id": "Fox2",
"Field": "King6",
"Value": "Alpha",
"Description": "Tango"
}
]
}
Doc2
{
"Title": "Bravo",
"data": [
{
"Id": "Kilo",
"Field": "Echo",
"Value": "Romeo",
"Description": "Jester"
}
]
}
我有两个这样的对象,并且正在尝试将一个对象的数据字段添加到另一个对象中-基本上是将一个数据"属性的数组中的数据添加到另一个对象中.
I have two of these objects, and am trying to add the data field from one into the other - basically add the data from one "data" property's array into the other's.
最终结果应该是这样的:
The end result should be like this:
{
"Title": "Alpha",
"data": [
{
"Id": "Fox2",
"Field": "King6",
"Value": "Alpha",
"Description": "Tango"
},
{
"Id": "Kilo",
"Field": "Echo",
"Value": "Romeo",
"Description": "Jester"
}
]
}
我正在尝试不对字符串进行反序列化和拧紧处理等操作.
I'm trying to do this without deserializing and screwing with combining strings, etc.
我尝试了这种变化:
var data = JObject.FromObject(doc1);
var editData = JObject.FromObject(doc2);
foreach (var editItem in editData.Property("data").Children())
{
data.Property("data").Add(editItem.Children());
}
但是,我不断收到这样的错误:
However, I keep getting an error like this:
Newtonsoft.Json.Linq.JProperty不能有多个值
Newtonsoft.Json.Linq.JProperty cannot have multiple values
.
我应该如何尝试合并数组?
How should I be attempting to combine the arrays?
推荐答案
为什么在最终对象中不包含"Title": "Bravo",
?
Why don't you include "Title": "Bravo",
in the final object?
我会这样做:
var j1 = (JObject)JsonConvert.DeserializeObject(json1);
var j2 = (JObject)JsonConvert.DeserializeObject(json2);
var jArray = new JArray(j1, j2);
var str = jArray.ToString();
编辑
var final = JsonConvert.SerializeObject(
new {Title=j1["Title"], data=j1["data"].Union(j2["data"])},
Newtonsoft.Json.Formatting.Indented);
这篇关于如何在Newtonsoft JSON.Net中合并来自两个JObjects的两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!