servarevitas3
servarevitas3

Reputation: 483

How do I combine two arrays from two JObjects in Newtonsoft JSON.Net?

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:

Doc1

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

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

Answers (1)

L.B
L.B

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

Related Questions