Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a json array into a property of a JObject with json.net

I am having difficulty figuring out how to add an array of json objects to an existing JObject. Say I have a JObject with just the "Modified" property, and I want to add another property "IntersectGroups" that contains an array of json objects, how can I do this? I Have a JObject[] that when I serialize it is exactly in the format I require, but I am looking for something like this: mainJObject.Add("IntersectGroups", myJObjectArray)

Here is an example of the final json I want when I serialize it.

...
"Modified": "2012-11-26T10:21:04.693",
"IntersectGroups": [
  {
    "Id": 1004,
    "UserId": 20003,
    "GroupId": 1001,
    "Admin": false,
    "Expires": "1900-01-01T00:00:00"
  },
  {
    "Id": 1003,
    "UserId": 20003,
    "GroupId": 1000,
    "Admin": false,
    "Expires": "1900-01-01T00:00:00"
  }
]
...

UPDATE

My final solution was to use the JArray object. A JArray is a JContainer, which is a JToken, which you can add to a JObject. My problem was that I was trying to use a JObject[], which was not a valid JToken

like image 795
bruchowski Avatar asked Apr 05 '13 00:04

bruchowski


People also ask

Can you put an array in a JSON file?

JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.

How do I write an array to a JSON file?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

What is JSON nested array?

Nested JSON is simply a JSON file with a fairly big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.


1 Answers

My final solution was to use the JArray object. A JArray is a JContainer, which is a JToken, which you can add to a JObject. My problem was that I was trying to use a JObject[], which was not a valid JToken

like image 84
bruchowski Avatar answered Sep 27 '22 20:09

bruchowski