将JObject添加到JObject

编程入门 行业动态 更新时间:2024-10-09 15:24:26
本文介绍了将JObject添加到JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的json结构:

I have a json structure like this:

var json = { "report": {}, "expense": {}, "invoices": {}, "projects": {}, "clients": {}, "settings": { "users": {}, "companies": {}, "templates": {}, "translations": {}, "license": {}, "backups": {}, } }

我想向json添加一个新的空对象,例如"report":{}.

I would like to add a new empty Object like "report":{} to the json

我的C#代码是这样的:

My C# code is like this:

JObject json = JObject.Parse(File.ReadAllText("path")); json.Add(new JObject(fm.Name));

但是它给了我一个例外:无法将Newtonsoft.Json.Linq.JValue添加到Newtonsoft.Json.Linq.JObject

But it it gives me a exception: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject

所以,如何将新的空JObject添加到json

So, how can I add a new and empty JObject to the json

预先感谢

推荐答案

出现此错误的原因是,您试图使用字符串构造JObject(该字符串将转换为JValue).为此,JObject不能直接包含JValue,也不能包含另一个JObject.它只能包含JProperties(依次包含其他JObjects,JArrays或JValues).

You are getting this error because you are trying to construct a JObject with a string (which gets converted into a JValue). A JObject cannot directly contain a JValue, nor another JObject, for that matter; it can only contain JProperties (which can, in turn, contain other JObjects, JArrays or JValues).

要使其正常运行,请将第二行更改为:

To make it work, change your second line to this:

json.Add(new JProperty(fm.Name, new JObject()));

正在运行的演示: dotnetfiddle/cjtoJn

更多推荐

将JObject添加到JObject

本文发布于:2023-11-28 20:30:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!