C# Web API JsonConvert.DeserializeObject反序列化后所有字段为null问题
问题
我尝试从JSON响应中读取数据,EmpResponse可展示正确数据,但经JsonConvert.DeserializeObject反序列化后的response对象所有字段均为null。
模型定义代码
public class AlertMessage { public string Title { get; set; } public string Message { get; set; } public string Severity { get; set; } } public class ItemLine { public string Description { get; set; } public int BilledAmount { get; set; } public int PaidAmount { get; set; } } public class CitationDetail { public string CitationNumber { get; set; } public string DefendantName { get; set; } public string DateofBirth { get; set; } public string VehicleTagNumber { get; set; } public string CaseType { get; set; } public string CaseStatus { get; set; } public string AppearanceDate { get; set; } public bool IsPayable { get; set; } public int FineSuspended { get; set; } public int FineServed { get; set; } public List<AlertMessage> AlertMessages { get; set; } public List<ItemLine> ItemLines { get; set; } } public class Root { public List<CitationDetail> CitationDetails { get; set; } public int CitationCount { get; set; } public bool SuccessfulSearch { get; set; } public string ErrorMessage { get; set; } }
控制器接口代码(内容未补充完整,以下为通用解决方案)
解决方案
- 首先输出
EmpResponse对应的原始JSON字符串,确认JSON结构和你定义的Root类完全匹配,不存在额外的嵌套层。比如JSON外层如果多了data字段包裹你的实际业务数据,直接反序列化为Root就会得到全空对象。 - 检查JSON属性名和C#模型属性名是否一致,如果JSON使用小驼峰命名,可以在反序列化时开启忽略大小写配置:
var deserializeSettings = new JsonSerializerSettings { PropertyNameCaseInsensitive = true }; var response = JsonConvert.DeserializeObject<Root>(EmpResponse, deserializeSettings);
- 如果属性名存在拼写差异或者命名规则不同,可通过
JsonProperty特性显式指定映射关系:
public class Root { // 示例:JSON中对应字段名为citation_details [JsonProperty("citation_details")] public List<CitationDetail> CitationDetails { get; set; } }
- 增加反序列化错误捕获,定位具体失败原因:
var deserializeSettings = new JsonSerializerSettings { Error = (sender, args) => { // 输出错误信息可直接定位哪个字段反序列化失败 Debug.WriteLine($"反序列化错误:{args.ErrorContext.Error.Message},出错字段:{args.ErrorContext.Member}"); args.ErrorContext.Handled = true; } }; var response = JsonConvert.DeserializeObject<Root>(EmpResponse, deserializeSettings);
- 检查类型匹配是否正确:比如JSON中数值类型字段如果以字符串形式存储,或者布尔值为字符串格式的
"true"/"false",需要对应修改模型属性类型或者添加自定义类型转换器。
内容的提问来源于stack exchange,提问作者Tdigges
相关产品推荐
相关产品推荐

