我有一个像这样的 json 结构:
var json =
{
"report": {},
"expense": {},
"invoices": {},
"projects": {},
"clients": {},
"settings": {
"users": {},
"companies": {},
"templates": {},
"translations": {},
"license": {},
"backups": {},
}
}
我想向 json 添加一个新的空对象,如“report”:{}
我的 C# 代码是这样的:
JObject json = JObject.Parse(File.ReadAllText("path"));
json.Add(new JObject(fm.Name));
但它给了我一个异常(exception):
Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject
那么,如何向 json 添加一个新的空 JObject
提前致谢
最佳答案
你得到这个错误是因为你试图用一个字符串构造一个JObject
(它被转换成一个JValue
)。 JObject
不能直接包含 JValue
,也不能直接包含另一个 JObject
;它只能包含 JProperties
(它又可以包含其他 JObjects
、JArrays
或 JValues
)。
要使其正常工作,请将第二行更改为:
json.Add(new JProperty(fm.Name, new JObject()));
关于c# - 将 JObject 添加到 JObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48168738/