如何为不存在对应字段的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
相关产品推荐
相关产品推荐

