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

如何使用C# JObject获取JSON嵌套元素并遍历Elenco提取flat、idPoint字段

实现方案

首先修正你现有代码的小问题:object是C#关键字,不能直接作为变量名,调整为jsonObject即可。
以下是遍历Elenco数组、匹配idPoint、提取flat数组的实现代码:

using Newtonsoft.Json.Linq;
using System.Linq;

// 解析JSON
JObject jsonObject = JObject.Parse(json);
// 拿到要匹配的目标Point值
string targetPoint = (string)jsonObject["Point"];
// 获取Elenco数组
JArray elencoList = (JArray)jsonObject["Elenco"];

// 方式1:循环遍历所有元素
foreach (JObject elencoItem in elencoList)
{
    // 提取当前项的idPoint值
    string currentIdPoint = (string)elencoItem["idPoint"];
    // 匹配判断
    if (currentIdPoint == targetPoint)
    {
        // 提取嵌套的flat数组,可直接转为double数组使用
        JArray flatArr = (JArray)elencoItem["values_"]["flat"];
        double[] flatValues = flatArr.ToObject<double[]>();
        
        // 此处补充你自己的业务逻辑即可
    }
}

// 方式2:用LINQ直接获取第一个匹配项,写法更简洁
var matchedItem = elencoList
    .Cast<JObject>()
    .FirstOrDefault(item => (string)item["idPoint"] == targetPoint);

if (matchedItem != null)
{
    double[] flatValues = matchedItem["values_"]["flat"].ToObject<double[]>();
    // 此处补充匹配后的业务逻辑
}

注意事项

  • 你给出的JSON示例存在语法错误:外层多了一对冗余大括号,Elenco数组的元素里多了一层无键的大括号,实际使用前请修正JSON语法,否则解析会抛出异常。
  • 如果你的实际业务中Elenco数组元素的idPoint、values_字段确实嵌套在其他子对象内,只需调整代码中的字段取值路径即可,比如elencoItem["嵌套字段名"]["idPoint"]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:09:03