I think you’re getting confused about what can hold what in JSON.Net.
- A
JToken
is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc. - A
JProperty
is a singleJToken
value paired with a name. It can only be added to aJObject
, and its value cannot be anotherJProperty
. - A
JObject
is a collection ofJProperties
. It cannot hold any other kind ofJToken
directly.
In your code, you are attempting to add a JObject
(the one containing the “banana” data) to a JProperty
(“orange”) which already has a value (a JObject
containing {"colour":"orange","size":"large"}
). As you saw, this will result in an error.
What you really want to do is add a JProperty
called “banana” to the JObject
which contains the other fruit JProperties
. Here is the revised code:
JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));