You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将扁平结构的Newtonsoft.Json.Linq.JArray转换为嵌套Fields结构?

将JArray转换为目标结构(C#)

完全可以实现这个转换,用Newtonsoft.Json的Linq to JSON API就能轻松完成,以下是具体代码:

首先确保你已经通过NuGet安装了Newtonsoft.Json包,然后使用以下代码:

using Newtonsoft.Json.Linq;

// 假设你的第二个JArray是secondJArray
JArray secondJArray = JArray.Parse(@"[
  {
    ""Relationship"": ""child"",
    ""FirstName"": ""Alex""
  }
]");

// 执行转换
var convertedJArray = new JArray(
    secondJArray.Select(obj => new JObject(
        new JProperty("Fields", new JArray(
            obj.Properties().Select(prop => new JObject(
                new JProperty("Key", prop.Name),
                new JProperty("Value", prop.Value)
            ))
        ))
    ))
);

// 可选:输出转换后的结果验证
Console.WriteLine(convertedJArray.ToString());

代码说明:

  • 用secondJArray.Select遍历原数组中的每个对象;
  • 对每个对象,创建新的JObject,其中包含名为Fields的属性;
  • Fields的值是新的JArray,通过遍历原对象的所有属性(obj.Properties()),将属性名作为Key、属性值作为Value,生成对应的JObject;
  • 最后把所有转换后的对象收集到新的JArray中。

运行代码后,convertedJArray的结构会和你提供的第一个JArray完全一致。

内容的提问来源于stack exchange,提问作者Nick ANV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:52:11