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

C#中如何将含Items的JSON转换为Key顶级数组结构?

JSON结构转换:移除Items节点并重组Key数组

原始JSON结构

{
  "Items": [
    {
      "Key": {
        "timestamp": "2022-11-06T20",
        "value": 100.80
      }
    },
    {
      "Key": {
        "timestamp": "2022-11-07T08",
        "value": 100.90
      }
    }
  ]
}

目标JSON结构

{
  "Key": [
    {
      "timestamp": "2019-01-08T20",
      "value": 12.44
    },
    {
      "timestamp": "2018-12-12 16:23:00",
      "value": 12.45
    }
  ]
}

需求

  • 顶层仅保留一个Key字段,对应包含timestamp和value的对象数组
  • 彻底移除Items父节点

你的错误代码

JObject obj = JObject.Parse(jsonOutput);
JObject newObj = new JObject();
new JProperty("KEY", new JArray(
    .Children<JProperty>()
    .Select(j => new JObject(
            new JProperty("timestamp", j.Value["timestamp"]),
            new JProperty("value", j.Value["value"])
        )
    )
));
jsonOutput = newObj.ToString();

正确实现

你的代码核心问题是未正确定位数据源(.Children<JProperty>()前缺少原始数组的引用),同时没有准确提取Items下的Key对象。以下是修正后的代码:

简洁版

JObject obj = JObject.Parse(jsonOutput);
var newObj = new JObject(
    new JProperty("Key", new JArray(
        obj["Items"].Children<JObject>().Select(item => item["Key"])
    ))
);
jsonOutput = newObj.ToString();

带空值判断的严谨版

如果需要处理Items不存在、为空或内部Key缺失的场景,可使用以下代码:

JObject obj = JObject.Parse(jsonOutput);
JArray keyArray = new JArray();

if (obj["Items"] is JArray itemsArray)
{
    foreach (var item in itemsArray.Children<JObject>())
    {
        if (item["Key"] is JObject keyObj)
        {
            keyArray.Add(keyObj);
        }
    }
}

var newObj = new JObject(new JProperty("Key", keyArray));
jsonOutput = newObj.ToString();

代码说明

  1. 解析原始JSON为JObject实例
  2. 定位到Items数组,遍历其中的每个对象,提取每个对象内的Key节点
  3. 将所有Key对象放入新的JArray,再作为顶层Key属性的值
  4. 最后将新构建的JObject转为JSON字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:45:40