使用System.Text.Json反序列化JSON遇List转换JsonException求助排查
问题排查与修复
核心错误点
- 反序列化类型不匹配:API返回的JSON是单个根对象(外层为
{}),但你尝试反序列化为List<Rootobject>(对应JSON数组[]),这是直接抛出JsonException的原因。 - 属性大小写不匹配:JSON中子对象的ID字段是大写开头的
"Id",但你的Match、Nomatch、Notfound类里的属性是小写的id,System.Text.Json默认大小写敏感,会导致这些属性无法被正确赋值。 - 冗余属性:
Rootobject类中定义的id属性在返回的JSON根节点中不存在,属于无效定义,建议删除。
修复步骤
1. 修正反序列化代码
将目标类型从List<Rootobject>改为单个JsonResp.Rootobject:
JsonResp.Rootobject? result = JsonSerializer.Deserialize<JsonResp.Rootobject>(ApiResponse);
2. 解决属性大小写问题
有两种方案可选:
方案一:给属性添加JsonPropertyName特性
明确指定JSON中的字段名:
public class Match { [JsonPropertyName("Id")] public string id { get; set; } } public class Nomatch { [JsonPropertyName("Id")] public string id { get; set; } } public class Notfound { [JsonPropertyName("Id")] public string id { get; set; } }
方案二:启用大小写不敏感配置
通过JsonSerializerOptions让序列化器忽略属性名的大小写差异:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; JsonResp.Rootobject? result = JsonSerializer.Deserialize<JsonResp.Rootobject>(ApiResponse, options);
3. 删除冗余属性
移除Rootobject类中无效的id属性:
public class Rootobject { [JsonPropertyName("matches")] public Match[] Matches { get; set; } [JsonPropertyName("nomatches")] public Nomatch[] Nomatches { get; set; } [JsonPropertyName("notfound")] public Notfound[] Notfound { get; set; } // 移除下面无效的属性定义 // [JsonPropertyName("id")] // public object id { get; set; } }
内容的提问来源于stack exchange,提问作者Sally
相关产品推荐
相关产品推荐

