JSON反序列化问题:API返回数据解析后对象为null无法获取name字段
问题排查与解决方案
问题根源
- JSON结构不匹配:返回的JSON根节点是一个包含
d属性的对象,而你直接尝试将整个JSON反序列化为List<Statuses>,序列化工具无法找到匹配的数组结构,因此返回null。 - 字段类型错误:
Statuses类中countedAbsence被定义为string类型,但JSON中该字段是布尔值false,类型不匹配会导致反序列化失败或数据异常。
修正方案
1. 新增根对象类
创建对应JSON根结构的类,用来包裹d数组:
public class StatusResponse { [JsonProperty("d")] public List<Statuses> StatusList { get; set; } }
2. 修正Statuses类字段类型
将countedAbsence的类型改为bool:
public class Statuses { [JsonProperty("__type")] public string __type { get; set; } [JsonProperty("countedAbsence")] public bool countedAbsence { get; set; } // 修正为bool类型 [JsonProperty("description")] public string description { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("schoolSystemExportIdentifier")] public string schoolSystemExportIdentifier { get; set; } [JsonProperty("shortCode")] public string shortCode { get; set; } [JsonProperty("shortName")] public string shortName { get; set; } [JsonProperty("statusId")] public string statusId { get; set; } }
3. 修改反序列化逻辑
先反序列化为根对象,再获取内部的StatusList:
// 替换原反序列化代码 var responseDto = SerializerHelper.Deserialize<StatusResponse>(output); var dtoDirectories = responseDto.StatusList; // 循环输出name字段 foreach (var status in dtoDirectories) { Console.WriteLine(status.name); }
完整修正后的代码
using CompassAPI; using Newtonsoft.Json; var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "{Removed for security}"); request.Headers.Add("CompassApiKey", "{removed for security}"); request.Headers.Add("Cookie", "{removed for security}"); var content = new StringContent("{\"schoolSystemType\": \"aus\"}", null, "application/json"); request.Content = content; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); string output = await response.Content.ReadAsStringAsync(); Console.WriteLine(output); // 修正后的反序列化逻辑 var responseDto = SerializerHelper.Deserialize<StatusResponse>(output); var dtoDirectories = responseDto.StatusList; foreach (var status in dtoDirectories) { Console.WriteLine(status.name); } Console.ReadLine(); // 新增根对象类 public class StatusResponse { [JsonProperty("d")] public List<Statuses> StatusList { get; set; } } public class Statuses { [JsonProperty("__type")] public string __type { get; set; } [JsonProperty("countedAbsence")] public bool countedAbsence { get; set; } [JsonProperty("description")] public string description { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("schoolSystemExportIdentifier")] public string schoolSystemExportIdentifier { get; set; } [JsonProperty("shortCode")] public string shortCode { get; set; } [JsonProperty("shortName")] public string shortName { get; set; } [JsonProperty("statusId")] public string statusId { get; set; } }
内容的提问来源于stack exchange,提问作者Michael van der Veeke
相关产品推荐
相关产品推荐

