C#反序列化多层JSON时移除content字段后result为空如何解决
问题解决方案
核心错误原因
- 实体类结构与JSON结构不匹配:原JSON中
result字段是单个对象,你定义的根实体类中将result声明为List<result>集合类型,导致反序列化时无法匹配结构,最终返回空数组。 - 反序列化目标类名不匹配:代码中反序列化用的是
jss.Deserialize<ApiResponse>(ResponseText),但你定义的根实体类名为Response,类名不一致导致反序列化失败。 - 潜在类型匹配问题:原JSON中
id、city、documentTypeId都是字符串格式的数值(如"id": "28"),如果序列化器未开启自动类型转换,直接声明为int会触发反序列化异常。 - 未配置忽略未知字段:如果序列化器默认遇到未知字段会终止反序列化,JSON中存在的
content字段没有对应实体属性,会导致反序列化失败。
修正后的代码
1. 调整实体类结构
// 根实体类,类名和反序列化使用的ApiResponse保持一致 public class ApiResponse { public int status { get; set; } // result是单个对象,不要声明为List public Result result { get; set; } } public class Result { // 不确定序列化器是否支持自动转类型的话,可以先声明为string public string id { get; set; } public string userName { get; set; } public string city { get; set; } public string cityName { get; set; } public string address { get; set; } public List<Document> documents { get; set; } } public class Document { public string documentTypeId { get; set; } public string fileName { get; set; } public string fileType { get; set; } // 直接删除content属性即可,无需额外配置 }
2. 调整反序列化配置
你请求序列化用的是Newtonsoft.Json,建议反序列化也用同一个库,避免规则差异:
if (responseApi.StatusCode == HttpStatusCode.OK) { ResponseText = responseApi.Content.ReadAsStringAsync().Result; // 配置忽略未知字段,自动忽略JSON里的content字段 var res = JsonConvert.DeserializeObject<ApiResponse>(ResponseText, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, PropertyNameCaseInsensitive = true }); }
如果坚持使用JavaScriptSerializer(已过时,不推荐),添加如下配置即可:
jss.IgnoreMissingProperties = true; var res = jss.Deserialize<ApiResponse>(ResponseText);
额外优化建议
- 不要同步调用
.Result,建议将方法改为异步,使用await调用PostAsync、ReadAsStringAsync等异步方法,避免线程死锁。 - C#类属性建议使用帕斯卡命名法(首字母大写),通过配置序列化器的属性命名策略实现和JSON驼峰命名的自动匹配,更符合C#编码规范。
内容的提问来源于stack exchange,提问作者fahime abouhamze
相关产品推荐
相关产品推荐

