Reputation: 483
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"
}
]
}
{
"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.
I've tried variations of this:
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 cannot have multiple values
.
How should I be attempting to combine the arrays?
Upvotes: 0
Views: 8230
Reputation: 116168
Why don't you include "Title": "Bravo",
in the final object?
I would do that way:
var j1 = (JObject)JsonConvert.DeserializeObject(json1);
var j2 = (JObject)JsonConvert.DeserializeObject(json2);
var jArray = new JArray(j1, j2);
var str = jArray.ToString();
EDIT
var final = JsonConvert.SerializeObject(
new {Title=j1["Title"], data=j1["data"].Union(j2["data"])},
Newtonsoft.Json.Formatting.Indented);
Upvotes: 3