如何在Newtonsoft JSON.Net中合并来自两个JObjects的两个数组?

编程入门 行业动态 更新时间:2024-10-28 00:21:51
本文介绍了如何在Newtonsoft JSON.Net中合并来自两个JObjects的两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个在其上运行过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的两个数组?

本文发布于:2023-10-24 23:52:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525350.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   数组   如何在   Newtonsoft   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!