JSON反序列化至IEnumerable<T>对象报错:无法创建填充ReasonCodeList
解决JSON转IEnumerable时的"Cannot create and populate list type ReasonCodeList"错误
这个错误我之前也碰到过,本质是JSON序列化器(比如Newtonsoft.Json)没法直接处理你自定义的ReasonCodeList集合类型,下面给你具体的解决方案:
核心原因
你的ReasonCodeList应该是一个自定义的列表类(比如继承自List<T>的自定义类),而序列化器默认只支持原生的集合类型(比如List<T>、IEnumerable<T>),对于自定义集合,如果没有合适的构造函数或序列化配置,就会出现无法实例化并填充的问题。
解决方案一:改用原生集合类型(推荐)
直接把实体类里的ReasonCodeList类型替换成List<ReasonCode>或者IEnumerable<ReasonCode>,这是最简单的解决方式:
正确的实体类定义
// 根对象类 public class AppointmentResponse { public string ErrorCode { get; set; } public string ErrorMessage { get; set; } public List<AppointmentReason> AppointmentReasonList { get; set; } } // 预约原因类 public class AppointmentReason { public string ClassCode { get; set; } public string ClassDescription { get; set; } public bool Active { get; set; } public bool IsPatientRelated { get; set; } // 把自定义的ReasonCodeList改成原生List<ReasonCode> public List<ReasonCode> ReasonCodeList { get; set; } } // 原因代码类 public class ReasonCode { public string Code { get; set; } public string Description { get; set; } public int Duration { get; set; } public bool Active { get; set; } }
反序列化代码
string json = "你的JSON字符串"; var response = JsonConvert.DeserializeObject<AppointmentResponse>(json); // 如果你需要IEnumerable<T>,直接取response.AppointmentReasonList即可,它本身就是IEnumerable<AppointmentReason> IEnumerable<AppointmentReason> reasonEnumerable = response.AppointmentReasonList;
解决方案二:保留自定义集合类(需额外配置)
如果因为业务需求必须保留ReasonCodeList自定义类,那需要给它添加无参构造函数,并实现序列化转换器:
自定义集合类+转换器
// 自定义集合类,添加无参构造函数和带集合参数的构造函数 public class ReasonCodeList : List<ReasonCode> { public ReasonCodeList() { } public ReasonCodeList(IEnumerable<ReasonCode> items) : base(items) { } } // 自定义JSON转换器 public class ReasonCodeListConverter : JsonConverter<ReasonCodeList> { public override ReasonCodeList ReadJson(JsonReader reader, Type objectType, ReasonCodeList existingValue, bool hasExistingValue, JsonSerializer serializer) { // 先反序列化成原生List,再转成自定义集合 var tempList = serializer.Deserialize<List<ReasonCode>>(reader); return new ReasonCodeList(tempList); } public override void WriteJson(JsonWriter writer, ReasonCodeList value, JsonSerializer serializer) { // 序列化时当作原生List处理 serializer.Serialize(writer, value as List<ReasonCode>); } }
给自定义集合类标记转换器
[JsonConverter(typeof(ReasonCodeListConverter))] public class ReasonCodeList : List<ReasonCode> { public ReasonCodeList() { } public ReasonCodeList(IEnumerable<ReasonCode> items) : base(items) { } }
这样配置后,序列化器就能正确识别并填充你的自定义ReasonCodeList了。
内容的提问来源于stack exchange,提问作者W.Harr
相关产品推荐
相关产品推荐

