Add JObject to JObject

前端 未结 3 1294
北海茫月
北海茫月 2021-01-03 23:21

I have a json structure like this:

相关标签:
3条回答
  • 2021-01-03 23:26

    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()));
    

    Working demo: https://dotnetfiddle.net/cjtoJn

    0 讨论(0)
  • 2021-01-03 23:26

    One more example

    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"),
        }
    };
    
    0 讨论(0)
  • 2021-01-03 23:37
    json["report"] = new JObject
        {
            { "name", fm.Name }
        };
    

    Newtonsoft is using more direct-like approach, where You can access any property via square brackets []. You just need to set the JObject, which have to be created based on Newtonsoft specifics.

    Full code:

    var json = JObject.Parse(@"
    {
        ""report"": {},
        ""expense"": {},
        ""invoices"": {},
        ""settings"": {
            ""users"" : {}
        },
    }");
    
    Console.WriteLine(json.ToString());
    
    json["report"] = new JObject
        {
            { "name", fm.Name }
        };
    
    Console.WriteLine(json.ToString());
    

    Output:

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

    As a reference, You can look at this link: https://www.newtonsoft.com/json/help/html/ModifyJson.htm

    0 讨论(0)
提交回复
热议问题