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

将API返回的JSON转换为C#对象时遇到序列化错误

JSON转C#对象序列化错误的解决方案

错误根源

  • 类型不匹配:API返回的是数组格式(外层由[]包裹),但代码尝试直接反序列化为单个CountryModel对象,导致根类型不兼容。
  • 结构不匹配:CountryModel的字段类型与JSON结构完全不符,例如name是嵌套对象而非字符串,tld是字符串数组而非单个字符串,idd、languages等均为复杂结构而非简单字符串。

修复步骤

1. 修正反序列化目标类型

将反序列化的目标改为数组或列表,匹配API返回的数组结构:

public static async Task getCountryData()
{
    var apiURL = "https://restcountries.com/v3.1/alpha/tto";

    using HttpClient client = new HttpClient(); // 使用using自动释放资源
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var jsonResults = await client.GetStringAsync(apiURL);
    // 反序列化为列表,而非单个对象
    List<CountryModel>? countryList = System.Text.Json.JsonSerializer.Deserialize<List<CountryModel>>(jsonResults);
    // 取列表第一个元素,访问name的common属性
    Console.WriteLine(countryList?.FirstOrDefault()?.Name?.Common);
}

2. 重新定义匹配JSON结构的C#类

根据API返回的JSON嵌套结构,定义对应的实体类:

// 对应name字段的嵌套结构
public class NameModel
{
    public string? Common { get; set; }
    public string? Official { get; set; }
    public Dictionary<string, NativeNameDetail>? NativeName { get; set; }
}

public class NativeNameDetail
{
    public string? Official { get; set; }
    public string? Common { get; set; }
}

// 对应idd字段的结构
public class IddModel
{
    public string? Root { get; set; }
    public List<string>? Suffixes { get; set; }
}

// 主实体类
public class CountryModel
{
    [JsonPropertyName("name")]
    public NameModel? Name { get; set; }
    public List<string>? Tld { get; set; }
    public string? Cca2 { get; set; }
    public string? Ccn3 { get; set; }
    public string? Cca3 { get; set; }
    public string? Cioc { get; set; }
    public IddModel? Idd { get; set; }
    public List<string>? Capital { get; set; }
    public List<string>? AltSpellings { get; set; }
    public string? Region { get; set; }
    public string? Subregion { get; set; }
    public Dictionary<string, string>? Languages { get; set; }
    // 其他字段可根据API完整返回继续补充
}

关键说明

  • 使用JsonPropertyName特性确保C#属性名与JSON键名严格匹配(若启用PropertyNameCaseInsensitive配置可省略)。
  • 数组类型用List<T>、嵌套对象用对应类、键值对结构用Dictionary<string, T>,完全对齐JSON类型。
  • 所有字段使用可空类型(?)处理可能缺失的字段,避免空引用异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:05:26