C#使用JsonConvert反序列化JSON对象报类型转换错误问题咨询
C# JSON反序列化报错解决方案
核心报错原因
- 传入的JSON字符串被外层额外双引号包裹,本质是把整个JSON对象转为了字符串字面量,不是合法的顶层JSON对象。
- 自动生成的Root类属性和JSON键不匹配:JSON根节点键为
TotalResulCount(单数)、SearchResults,但类属性是totalResulCounts(复数)、searchResults,单复数差异无法匹配。 - 反序列化方法未指定泛型目标类型,默认返回JObject,无法直接赋值给自定义类。
修复步骤
1. 修正实体类映射(二选一即可)
方式一:直接修改属性名与JSON键完全一致
using System.Collections.Generic; public class TotalResulCount { public int ResultCount { get; set; } } public class SearchResult { public int ID { get; set; } public string LPWLastName { get; set; } public string LPWFirstName { get; set; } public string LPWLicenseNumber1 { get; set; } public string LPWLicenseTitle { get; set; } public string LPWLicenseStatusCategory { get; set; } public string LPWLicensee { get; set; } public string LPWLicenseNumber2 { get; set; } public string LPWLicenseTypeDescription { get; set; } public string LPWLicenseType { get; set; } public string LPWIssueDate { get; set; } public string LPWApprovalDate { get; set; } public string LPWExpirationDate { get; set; } } public class Root { public List<TotalResulCount> TotalResulCount { get; set; } public List<SearchResult> SearchResults { get; set; } }
方式二:通过特性显式指定映射(保留原有属性名)
using Newtonsoft.Json; using System.Collections.Generic; public class Root { [JsonProperty("TotalResulCount")] public List<TotalResulCount> totalResulCounts { get; set; } [JsonProperty("SearchResults")] public List<SearchResult> searchResults { get; set; } }
2. 修正传入的JSON格式
去掉JSON字符串外层多余的包裹引号,确保传入的是合法JSON对象,即myJsonResponse的内容为:
{ "TotalResulCount": [{"ResultCount":1}], "SearchResults": [{"ID":1,"LPWLastName":"","LPWFirstName":"","LPWLicenseNumber1":"","LPWLicenseTitle":"Clinical Genetic Molecular Biologist Scientist","LPWLicenseStatusCategory":"Active","LPWLicensee":"","LPWLicenseNumber2":"","LPWLicenseTypeDescription":"(CGMBS) Clinical Genetic Molecular Biologist Scientist","LPWLicenseType":"MTP","LPWIssueDate":"11/21/2013","LPWApprovalDate":"11/15/2019","LPWExpirationDate":"11/19/2021"}] }
3. 修正反序列化代码
添加泛型参数指定目标类型:Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
内容的提问来源于stack exchange,提问作者karthik kasula
相关产品推荐
相关产品推荐

