DeathAndTaxes
DeathAndTaxes

Reputation: 21

JObject JSON Parsing Nested Object

I'm trying to parse JSON into an array that is formatted like the following:

{
    "company": [
        [
            {
                "id": 1,
                "name": "Test Company1"
            },
           {
                "id": 2,
                "name": "Test Company2"
            }
        ]
    ]
}

I'm using Newtonsoft JObjects to do this. I have the following code so far, which gets me to the "company" object:

JObject joResponse = JObject.Parse(json);
JArray arr = (JArray)joResponse["company"];

But there is only one value in the array, it's one single value with the all of the JSON nodes in it:

    [
        {
            "id": 1,
            "name": "Test Company1"
        },
       {
            "id": 2,
            "name": "Test Company2"
        }
    ]

So essentially I need to get to that 2nd level, but the 2nd level inside of "company" isn't named so I'm not sure how to access it.

Upvotes: 2

Views: 2470

Answers (2)

Charlieface
Charlieface

Reputation: 71578

The easiest way to do this is to create classes to hold each object type. This is made more complex by the fact that company is actually an array of arrays, for some reason.

class Root
{
    public List<List<Company>> companies { get; set; }
}

class Company
{
    public int id { get; set; }
    public string name { get; set; }
}

Then you simply deserialize into the root object

var result = JsonConvert.DeserializeObject<Root>(json);

var companies = result.companies.SelectMany(c => c).ToList();

Upvotes: 0

Rans
Rans

Reputation: 602

You can use something like this:

JToken arr = joResponse["company"]?.Children().First()[1];

Or:

JToken arr = joResponse["company"]?[0]?[1];

Upvotes: 3

Related Questions