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

若如初见. 提交于 2019-12-12 03:56:30

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/12516510/how-do-i-combine-two-arrays-from-two-jobjects-in-newtonsoft-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!