C#使用JsonConvert反序列化JSON返回null问题排查求助
问题排查及解决方案
核心错误原因
- RootData类属性类型映射错误:JSON根节点下的
educations是对象类型(包含count和education两个子字段),但你当前RootData中对应educations的属性edu1类型为education[],类型不匹配导致反序列化直接失败,你定义的educationss类完全没有被用到。 - education类字段映射完全错误:JSON中education节点下的
expiry是对象类型,内部包含布尔类型的monthlyExpire字段,你当前定义的monthlyExpire属性不仅类型错配为expiry[],也没有映射到上层的expiry字段。 - 属性名大小写不匹配:education类中的
LibraryAllowed首字母大写,JSON中对应字段为小写开头的libraryAllowed,没有加JsonProperty映射会导致匹配失败;同理SportsGroup字段也存在映射缺失问题。 - 补充:你贴出的JSON片段不完整,末尾
"SportsGroup"没有闭合,实际调用时需要确保接口返回的是完整合法的JSON结构,否则也会反序列化失败。
修复方案
第一步:修正实体类定义
// 根节点类 public class RootData { [JsonProperty(PropertyName = "educations")] public Educationss Educations { get; set; } } // 对应educations对象的类 public class Educationss { [JsonProperty(PropertyName = "count")] public int Count { get; set; } [JsonProperty(PropertyName = "education")] public Education[] EducationList { get; set; } } // 对应expiry对象的类(之前缺失) public class Expiry { [JsonProperty(PropertyName = "monthlyExpire")] public bool MonthlyExpire { get; set; } } // 对应education对象的类 public class Education { [JsonProperty(PropertyName = "studId")] public string StudId { get; set; } [JsonProperty(PropertyName = "joinDate")] public DateTime JoinDate { get; set; } [JsonProperty(PropertyName = "regDate")] public DateTime RegDate { get; set; } [JsonProperty(PropertyName = "enrolled")] public bool Enrolled { get; set; } [JsonProperty(PropertyName = "eduId")] public string EduId { get; set; } [JsonProperty(PropertyName = "pId")] public string PId { get; set; } [JsonProperty(PropertyName = "startDate")] public DateTime StartDate { get; set; } // 修正expiry字段映射 [JsonProperty(PropertyName = "expiry")] public Expiry Expiry { get; set; } [JsonProperty(PropertyName = "reRegistration")] public string ReRegistration { get; set; } [JsonProperty(PropertyName = "refreeId1")] public string RefreeId1 { get; set; } [JsonProperty(PropertyName = "refreeId2")] public string RefreeId2 { get; set; } [JsonProperty(PropertyName = "tutor")] public bool Tutor { get; set; } [JsonProperty(PropertyName = "libraryAllowed")] public bool LibraryAllowed { get; set; } [JsonProperty(PropertyName = "sports")] public string Sports { get; set; } [JsonProperty(PropertyName = "sendNotification")] public bool SendNotification { get; set; } [JsonProperty(PropertyName = "ccEmail")] public string CcEmail { get; set; } [JsonProperty(PropertyName = "isTest")] public bool IsTest { get; set; } // 补充SportsGroup字段映射,可根据实际JSON结构调整类型,如果是数组就改为对应数组类型 [JsonProperty(PropertyName = "SportsGroup")] public string SportsGroup { get; set; } }
第二步:反序列化代码调整(可选,增加错误排查)
可添加异常捕获快速定位问题:
string rawResponse = apiDataResponse.Content; // 先判断返回内容是否为空 if(string.IsNullOrEmpty(rawResponse)) { // 处理接口返回空的逻辑 } try { var result = JsonConvert.DeserializeObject<RootData>(rawResponse); } catch(Exception ex) { // 打印ex.Message即可查看具体反序列化错误原因 }
内容的提问来源于stack exchange,提问作者Patali
相关产品推荐
相关产品推荐

