【问题标题】:Add JObject to JObject将 JObject 添加到 JObject
【发布时间】:2018-06-18 12:29:32
【问题描述】:

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

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

提前致谢

【问题讨论】:

标签: c# json linq json.net


【解决方案1】:

您收到此错误是因为您尝试使用字符串构造 JObject(它被转换为 JValue)。就此而言,JObject 不能直接包含JValue,也不能直接包含另一个JObject;它只能包含JProperties(它又可以包含其他JObjectsJArraysJValues)。

要使其正常工作,请将您的第二行更改为:

json.Add(new JProperty(fm.Name, new JObject()));

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

【讨论】:

    【解决方案2】:

    再举一个例子

    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"),
        }
    };
    

    【讨论】:

      【解决方案3】:
      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

      【讨论】:

        猜你喜欢
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2019-03-20
        相关资源
        最近更新 更多