【问题标题】:Deserializing Api Object with JSON.net使用 JSON.net 反序列化 Api 对象
【发布时间】:2017-07-14 05:42:02
【问题描述】:

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

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

我目前正在获取元 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 状态元素。

我尝试在元类型中放置一个列表,例如:

    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;

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

'无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1'

环顾四周,找不到直接解决我问题的方法。

【问题讨论】:

    标签: c# json json.net deserialization


    【解决方案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 应该看起来像(identif 必须是一个数组):(.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;}
    }
    

    【讨论】:

    • 你是救生员!谢谢!简直不敢相信这就是全部!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    相关资源
    最近更新 更多