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

通用JSON反序列化工具在特定场景下失效问题求助

问题根源
  1. JSON根对象的键为"Theaters"(大写开头),但TheaterList类中对应的字段是小写的theaters,System.Text.Json默认区分大小写,导致无法匹配,最终返回空列表。
  2. Get方法中多余的Convert.ChangeType完全没必要——JsonSerializer.Deserialize<T>已直接返回T类型,强制转换反而可能引发异常。
  3. 第二个影院对象中的parks数组无法映射到Theater类的shows属性,会导致该部分数据丢失。
解决方案

1. 修正类定义,匹配JSON键名

有两种方式解决大小写与字段映射问题:

方式一:用JsonPropertyName特性指定映射关系

修改类定义,确保属性与JSON键一一对应:

using System.Text.Json.Serialization;

public class Theater
{
    public Theater()
    {
        shows = new List<ShowBase>();
    }
    public string id { get; set; }
    public string name { get; set; }
    public string slug { get; set; }

    // 匹配JSON中的"shows"字段
    [JsonPropertyName("shows")]
    public ICollection<ShowBase> shows { get; set; }

    // 可选:如果需要接收"parks"数据,添加该属性
    [JsonPropertyName("parks")]
    public ICollection<ShowBase> parks { get; set; }
}

public class ShowBase
{
    public string id { get; set; }
    public string name { get; set; }
}

public class TheaterList
{
    public TheaterList()
    {
        Theaters = new List<Theater>();
    }
    // 匹配JSON根对象的"Theaters"键
    [JsonPropertyName("Theaters")]
    public List<Theater> Theaters { get; set; }
}

方式二:配置序列化器忽略大小写

如果不想修改类结构,可在反序列化时开启大小写不敏感:

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
var data = JsonSerializer.Deserialize<T>(json, options);

2. 简化Get方法,移除多余转换

修改后的Get方法如下,去掉不必要的类型转换:

public virtual async Task<T> Get<T>()
{
    var response = await client.GetAsync(URL);
    Console.WriteLine(response.IsSuccessStatusCode);
    string json = await response.Content.ReadAsStringAsync();
    
    // 启用大小写不敏感配置(可选,若用方式一可省略)
    var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
    var data = JsonSerializer.Deserialize<T>(json, options);
    
    return data;
}

3. 正确调用Get方法

使用修正后的TheaterList作为泛型参数调用:

var result = await TheaterGetter.Get<TheaterList>();

4. 处理JSON中的parks字段

如果第二个影院的parks也是演出数据,可选择:

  • 在Theater类中添加parks属性并映射(如方式一中的代码)
  • 自定义JSON转换器,将parks数据合并到shows列表中

关于GetList方法的说明

你的GetList方法泛型参数逻辑错误——JSON根对象不是直接的数组,而是包含Theaters数组的对象,因此不需要这个方法,直接使用修正后的Get<TheaterList>即可。

内容的提问来源于stack exchange,提问作者JerseyDuke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:47:21