Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add JObject to JObject

I have a json structure like this:

var json =   {    "report": {},    "expense": {},    "invoices": {},    "projects": {},    "clients": {},    "settings": {      "users": {},      "companies": {},      "templates": {},      "translations": {},      "license": {},      "backups": {},    }  }

I would like to add a new empty Object like "report":{} to the json

My C# code is like this:

JObject json = JObject.Parse(File.ReadAllText("path")); json.Add(new JObject(fm.Name)); 

But it it gives me a exception: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject

So, how can I add a new and empty JObject to the json

Thanks in advance

like image 907
DoobieAsDave Avatar asked Jan 09 '18 12:01

DoobieAsDave


People also ask

How do I add Jobjects to JObject?

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.

How do you value a JObject?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

What is JObject C#?

JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft.


1 Answers

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

like image 105
Brian Rogers Avatar answered Oct 07 '22 18:10

Brian Rogers