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

如何实现JObject在单值与多值场景下的正常迭代

兼容JSON单对象与多数组的迭代解决方案

问题核心是JSON序列化时,单个元素会被处理为JObject,多个元素则是JArray,直接foreach遍历会出现两种不同的行为:

  • 多数组场景:遍历的是数组中的每个JObject,能正常获取#text
  • 单对象场景:遍历的是JObject的属性(如@Seq、#text),导致你拿到的是单个属性节点而非完整对象

修复代码

先统一将目标节点转为数组类型,再进行迭代:

// 获取目标节点
var installInstructionNode = atpmessage["AUTOPILOTMessage"]["AUTOPILOTBody"]["OrderHeader"]["InstallationInstructions"]["InstallationInstruction"];

// 统一处理为JArray:如果是单个JObject就包装成数组,否则直接用原数组
var installInstructions = installInstructionNode.Type == JTokenType.Object 
    ? new JArray(installInstructionNode) 
    : installInstructionNode as JArray;

// 正常遍历
foreach (var installinst in installInstructions)
{
    // 注意:如果是多序列,这里直接赋值会覆盖之前的值,建议改为集合存储(比如List<string>)
    responseISGEMEA.data.install_instruct = installinst["#text"].ToString();
}

额外说明

原代码在单对象场景出错,是因为foreach遍历JObject时,会迭代它的所有子属性(即@Seq和#text这两个JProperty),此时installinst是属性节点而非完整对象,自然无法通过installinst["#text"]获取值。统一转为数组后,遍历的始终是完整的JObject,就能兼容两种场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:05:21