将JObject添加到JObject

Doo*_*ave 14 c# linq json json.net

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

var json = 
{
  "report": {},
  "expense": {},
  "invoices": {},
  "projects": {},
  "clients": {},
  "settings": {
    "users": {},
    "companies": {},
    "templates": {},
    "translations": {},
    "license": {},
    "backups": {},
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在json中添加一个新的空对象,如"report":{}

我的C#代码是这样的:

JObject json = JObject.Parse(File.ReadAllText("path"));
json.Add(new JObject(fm.Name));
Run Code Online (Sandbox Code Playgroud)

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

那么,我怎样才能在json中添加一个新的空JObject

提前致谢

Bri*_*ers 18

您收到此错误是因为您正在尝试JObject使用字符串构造一个字符串(将其转换为a JValue).A JObject不能直接包含一个JValue,也不能包含另一个JObject; 它只能包含JProperties(反过来,它可以包含其他JObjects,JArraysJValues).

要使其工作,请将第二行更改为:

json.Add(new JProperty(fm.Name, new JObject()));
Run Code Online (Sandbox Code Playgroud)

工作演示:https://dotnetfiddle.net/cjtoJn


Ser*_*yev 9

再举一个例子

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"),
    }
};
Run Code Online (Sandbox Code Playgroud)


Tat*_*ved 5

json["report"] = new JObject
    {
        { "name", fm.Name }
    };
Run Code Online (Sandbox Code Playgroud)

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());
Run Code Online (Sandbox Code Playgroud)

输出:

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

{
  "report": {
    "name": "SomeValue"
  },
  "expense": {},
  "invoices": {},
  "settings": {
    "users": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

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