user6443295
user6443295

Reputation:

Deserializing Api Object with JSON.net

Let me explain my problem. So I have JSON:

    {"num":20, "meta":[{"id":312, "identif":{"type":true,"status":false}}}]}

I am currently grabbing the meta id field with:

    var id = JsonConvert.DeserializeObject<typeObj>
    (returnJSON(ApiUrl)).meta[0].id;

class to refrence:

    class typeObj
    {
        public int num {get; set; }
        public List<metatypes> meta {get; set;}
    }
    class metatypes
    {
        public int id {get; set;}
    }

The issue doesn't lay here though. I am trying to get the indentif status element from meta.

I have tried putting a list in metatypes like:

    class metatypes
    {
        public int id {get; set;}
        public List<idtypes> identif {get; set;}
    }
    class idtypes
    {
        public bool type {get; set;}
        public bool status {get; set;}
    }

Calling it with:

    var id = JsonConvert.DeserializeObject<typeObj>
    (returnJSON(ApiUrl)).meta[0].identif[0].status;

But when I try this it returns

'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1'

Looked around and couldn't find a direct solution to my problem.

Upvotes: 1

Views: 61

Answers (1)

tinamou
tinamou

Reputation: 2292

You have an incorrect json for the desired structure:

Given classes:

class typeObj
{
    public int num {get; set; }
    public List<metatypes> meta {get; set;}
}

class metatypes
{
    public int id {get; set;}
    public List<idtypes> identif {get; set;}
}
class idtypes
{
    public bool type {get; set;}
    public bool status {get; set;}
}

Your json should look like (identif must be an array): (.NET Fiddle)

{"num":20, "meta":[{"id":312, "identif":[{"type":true,"status":false}]}]}

For the json in question your classes should be like this: (.NET Fiddle)

class typeObj
{
    public int num {get; set; }
    public List<metatypes> meta {get; set;}
}

class metatypes
{
    public int id {get; set;}
    public idtypes identif {get; set;}
}
class idtypes
{
    public bool type {get; set;}
    public bool status {get; set;}
}

Upvotes: 1

Related Questions