将 JObject 添加到 JObject

35

我有一个像这样的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));

但是它给我一个异常:

无法将 Newtonsoft.Json.Linq.JValue 添加到 Newtonsoft.Json.Linq.JObject

那么,我该如何向 JSON 中添加一个新的空 JObject?

提前致谢。


JObject没有接受JValue参数的构造函数。[https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm] - gvmani
json.Add(new JObject().Add("test",new JValue(fm.Name))); - gvmani
3个回答

39
你之所以会遇到这个错误,是因为你试图用一个字符串构造一个 JObject(它会被转换为 JValue)。JObject 不能直接包含 JValue,也不能直接包含另一个 JObject,但它可以包含 JProperties(而 JProperties 则可以包含其他的 JObject、JArray 或者 JValue)。
要让代码正常工作,请将你的第二行代码改成这样:
json.Add(new JProperty(fm.Name, new JObject()));

演示链接:https://dotnetfiddle.net/cjtoJn


15

再举一个例子

var jArray = new JArray {
    new JObject
    {
        new JProperty("Property1",
            new JObject
            {
                new JProperty("Property1_1", "SomeValue"),
                new JProperty("Property1_2", "SomeValue"),
            }
        ),
        new JProperty("Property2", "SomeValue"),
    }
};

8
json["report"] = new JObject
    {
        { "name", fm.Name }
    };

Newtonsoft正在使用更直接的方法,您可以通过方括号[]访问任何属性。 您只需要设置JObject,该对象必须基于Newtonsoft具体规范创建。

完整代码:

var json = JObject.Parse(@"
{
    ""report"": {},
    ""expense"": {},
    ""invoices"": {},
    ""settings"": {
        ""users"" : {}
    },
}");

Console.WriteLine(json.ToString());

json["report"] = new JObject
    {
        { "name", fm.Name }
    };

Console.WriteLine(json.ToString());

输出:

{
  "report": {},
  "expense": {},
  "invoices": {},
  "settings": {
    "users": {}
  }
}

{
  "report": {
    "name": "SomeValue"
  },
  "expense": {},
  "invoices": {},
  "settings": {
    "users": {}
  }
}

作为参考,您可以查看此链接:https://www.newtonsoft.com/json/help/html/ModifyJson.htm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接