首页 > 解决方案 > 如何在 Csharp 中反序列化 JSON 数组

问题描述

下面是我从 API 获取的 Json 有效负载:

[
  {
    "id": "8c0e33ea-51af-44e0-8cb5-ef93703a4e6c",
    "storeId": "xyz",
    "name": "009DI",
    "styleColors": []
  },
  {
    "id": "f6284195-0f58-4f6b-a3b8-d5d22d1f7e63",
    "storeId": "abc",
    "name": "A001A",
    "styleColors": []
  }
]

为反序列化创建的类:

    public class BINobjects
    {
        [JsonProperty(PropertyName = "binid")]
        public string binid { get; set; }

        [JsonProperty(PropertyName = "storeId")]
        public string storeId { get; set; }

        [JsonProperty(PropertyName = "binname")]
        public string binname { get; set; }       
    }
    public class BINdetails
    {
        [JsonProperty(PropertyName = "BINobjects")]
        //public pages pages { get; set; }
        public IList<BINobjects> BINobjects { get; set; }        
    }

下面是我如何尝试将其反序列化为 BINdetails 对象列表

BINobjects BINdetails = JsonConvert.DeserializeObject<List<BINobjects>>(result);

错误:无法将“system.collections.generic.list”隐式转换为“tools.binobjects”。但是,下面的代码有效,但只能从源中读取 1 列。 var str = JsonConvert.DeserializeObject<List<BINobjects>>(result); 有没有办法直接读取对象而不是变量。我是任何可行的都很好。

标签: json-deserialization

解决方案


我通过编辑类属性名称来修复它:

public class BINobjects
    {
        [JsonProperty(PropertyName = "id")]
        public string binid { get; set; }

        [JsonProperty(PropertyName = "storeId")]
        public string storeId { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string binname { get; set; }

    }

然后读入变量:

var str = JsonConvert.DeserializeObject<List<BINobjects>>(result);

推荐阅读