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

如何为不存在对应字段的JObject添加嵌套字段?

如何给JObject添加嵌套字段

你原来的写法会报错,因为当dataObject中不存在currentSection这个键时,dataObject[currentSection]返回的是JToken.Null而非JObject,此时无法直接通过[key]赋值。正确的做法是先检查并创建嵌套的JObject,再添加键值对。

基础实现代码

JObject dataObject = new JObject();

// 获取或创建currentSection对应的嵌套JObject
JObject sectionObject = dataObject[currentSection] as JObject;
if (sectionObject == null)
{
    sectionObject = new JObject();
    dataObject[currentSection] = sectionObject;
}

// 给嵌套对象添加目标键值对
sectionObject[key] = val;

简化写法(C# 7.0+ 模式匹配)

JObject dataObject = new JObject();

if (!(dataObject[currentSection] is JObject section))
{
    section = new JObject();
    dataObject[currentSection] = section;
}
section[key] = val;

执行上述代码后,序列化dataObject就能得到你想要的JSON结构:

{
    "currentSection": {
        "key": "value"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:01:10