两个数组合成一个json对象_如何在Newtonsoft JSON.Net中合并来自两个JObjects的两个数组?...

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值