我有一个像这样的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
发布评论