将JObject添加到JObject [英] Add JObject to 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()));
正在运行的演示: https://dotnetfiddle.net/cjtoJn
这篇关于将JObject添加到JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!