DZetko DZetko - 1 year ago 107
JSON Question

Json.NET: Parsing object array of unknown length

I am trying to parse a JSON array that looks something like this:

"chatName": "Test",
"users": [
"someBooleanValue": true,
"someObjects": {
"object1": "someObjectValue1",
"object2": "someObjectValue2",

Is there a way to parse the someObjects array of objects, when I don't know how many objects the array will have before I start processing the JSON file?

All the parsing is done using Json.NET.

Answer Source

You can use dynamic for someObjects. Code can look like:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
    public string chatName { get; set; }
    public List<string> users { get; set; }
    public bool someBooleanValue { get; set; }
    public dynamic someObjects { get; set; }

public class Program
    static public void Main()
        string j = "{\"chatName\": \"Test\",\"users\": [\"User1\",\"User2\"],\"someBooleanValue\": true,\"someObjects\": {\"object1\": \"someObjectValue1\",\"object2\": \"someObjectValue2\"}}";

        RootObject ro = JsonConvert.DeserializeObject<RootObject>(j);