You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.


排查与解决方法

  1. 核心问题:JSON结构不匹配
    API返回的是一个根对象,而非直接的数组。你试图将整个根对象反序列化为List<PresenceDay>,自然会抛出类型不匹配的异常。

  2. 定义根响应类
    创建对应整个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; }
    }
    
  3. 修正反序列化逻辑
    先反序列化为根对象,再提取Data属性中的数组:

    var jsonResponse = await httpClient.GetStringAsync("api-url");
    var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse);
    var presenceDays = apiResponse?.Data;
    
  4. 额外优化检查

    • 确保所有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:01:33