使用JSON.net反序列化Api对象

时间:2017-07-14 05:42:03

标签: c# json json.net deserialization

让我解释一下我的问题。 所以我有JSON:

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

我目前正在抓取meta id字段:

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

类参考:

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

但问题并不在于此。我试图从meta获取indentif status元素。

我尝试过将列表放在元类型中,例如:

    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;}
    }

用以下方式调用:

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

但是当我尝试这个时它会返回

&#39;无法将当前的JSON对象(例如{&#34; name&#34;:&#34; value&#34;})反序列化为类型System.Collections.Generic.List`1& #39;

环顾四周,无法直接解决我的问题。

1 个答案:

答案 0 :(得分:1)

您所需的结构的json不正确:

鉴于课程:

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;}
}

您的json应该看起来像(标识必须是数组):( .NET Fiddle

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

对于有问题的json,你的类应该是这样的:(.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;}
}
相关问题