C# API JSON响应反序列化为List<PresenceDay>失败求助
问题:反序列化API JSON响应为List时抛出JsonException
我是C#开发新手,调用API获取JSON响应后,尝试将其反序列化为List<PresenceDay>对象时抛出System.Text.Json.JsonException错误,查阅相关资料仍无法解决。API返回的JSON包含code、status、message、data字段,其中data为嵌套数组;已定义PresenceDay类并配置JsonPropertyName映射;反序列化代码无编译错误但运行报错,相关信息如下:
API返回JSON示例
{ "code": 200, "status": "success", "message": "获取成功", "data": [ { "date": "2024-01-01", "status": "present", "details": [ { "time": "09:00", "type": "checkin" } ] }, { "date": "2024-01-02", "status": "absent", "details": [] } ] }
PresenceDay类代码
using System.Text.Json.Serialization; public class PresenceDay { [JsonPropertyName("date")] public string Date { get; set; } [JsonPropertyName("status")] public string Status { get; set; } [JsonPropertyName("details")] public List<PresenceDetail> Details { get; set; } } public class PresenceDetail { [JsonPropertyName("time")] public string Time { get; set; } [JsonPropertyName("type")] public string Type { get; set; } }
Program.cs反序列化代码
using System.Text.Json; var jsonResponse = await httpClient.GetStringAsync("api-url"); var presenceDays = JsonSerializer.Deserialize<List<PresenceDay>>(jsonResponse);
错误信息
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[PresenceDay]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
排查与解决方法
核心问题:JSON结构不匹配
API返回的是一个根对象,而非直接的数组。你试图将整个根对象反序列化为List<PresenceDay>,自然会抛出类型不匹配的异常。定义根响应类
创建对应整个JSON结构的类,用来接收完整响应:using System.Text.Json.Serialization; public class ApiResponse { [JsonPropertyName("code")] public int Code { get; set; } [JsonPropertyName("status")] public string Status { get; set; } [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("data")] public List<PresenceDay> Data { get; set; } }修正反序列化逻辑
先反序列化为根对象,再提取Data属性中的数组:var jsonResponse = await httpClient.GetStringAsync("api-url"); var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse); var presenceDays = apiResponse?.Data;额外优化检查
- 确保所有
JsonPropertyName的拼写、大小写与JSON字段完全一致 - 若JSON中存在可选字段或null值,将类属性标记为可空(如
public string? Date { get; set; }) - 可添加反序列化选项增强兼容性:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, // 忽略字段大小写匹配 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse, options);
- 确保所有
内容的提问来源于stack exchange,提问作者Lucie LE COZ
相关产品推荐
相关产品推荐

