【问题标题】:Converting JSON data from an API to a C# object将 JSON 数据从 API 转换为 C# 对象
【发布时间】:2022-12-14 07:43:57
【问题描述】:

我正在尝试将 JSON 数据从 API 转换为 C# 对象,但出现以下错误:

无法将 JSON 值转换为 CountriesDemo.Models.CountryModel。路径:$ |行号:0 | BytePositionInLine:1

我的功能:

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

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var jsonResults = await client.GetStringAsync(apiURL);
    CountryModel? cshrpObj = System.Text.Json.JsonSerializer.Deserialize< CountryModel >(jsonResults);
    Console.WriteLine(cshrpObj?.name);
}

C#类:

public class CountryModel
{
    public string? name { get; set; }
    public string tld { get; set; } = null!;
    public string cca2 { get; set; } = null!;
    public string ccn3 { get; set; } = null!;
    public string cca3 { get; set; } = null!;
    public string cioc { get; set; } = null!;
    public string currency { get; set; } = null!;
    public string idd { get; set; } = null!;
    public string capital { get; set; } = null!;
    public string altSpellings { get; set; } = null!;
    public string region { get; set; } = null!;
    public string subregion { get; set; } = null!;
    public string languages { get; set; } = null!;
    public string translations { get; set; } = null!;
    public string latlng { get; set; } = null!;
    public string demonym { get; set; } = null!;
    public string landlocked { get; set; } = null!;
    public string borders { get; set; } = null!;
    public string area { get; set; } = null!;
}

API 数据片段

[
  {
    "name": {
        "common": "United States",
        "official": "United States of America",
        "nativeName": {
            "eng": {
                "official": "United States of America",
                "common": "United States"
            }
        }
    },
    "tld": [
        ".us"
    ],
    "cca2": "US",
    "ccn3": "840",
    "cca3": "USA",
    "cioc": "USA",
    "independent": true,
    "status": "officially-assigned",
    "unMember": true,
]

【问题讨论】:

  • 除非您展示从 api 收到的 json 是什么样子,否则我们帮不了您。
  • API url 是公开的并返回 JSON,参见:restcountries.com/v3.1/alpha/tto

标签: c# system.text.json


【解决方案1】:

不幸的是你的 json 模型不正确。对于你发布的 json,你需要这个模型

    List<Country> myDeserializedClass = JsonSerializer.Deserialize<List<Country>>(jsonResults);

public class Country
{
    public Name 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 bool independent { get; set; }
    public string status { get; set; }
    public bool unMember { get; set; }
}
public class Eng
{
    public string official { get; set; }
    public string common { get; set; }
}

public class Name
{
    public string common { get; set; }
    public string official { get; set; }
    public NativeName nativeName { get; set; }
}

public class NativeName
{
    public Eng eng { get; set; }
}

【讨论】:

  • 谢谢你的例子!!为什么要将 ttd 设为 List<string> 而不是 string[]
  • @ChrisJ 如果你想要一个字符串数组,只需将 List<string> 替换为 string[]。我不知道你打算用这些数据做什么。在大多数情况下,列表更有用。
【解决方案2】:

那是因为您所指的 endpoint 返回一个对象数组,而不是直接返回一个对象。

尝试这个:

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

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var jsonResults = await client.GetStringAsync(apiURL);
    CountryModel[] cshrpObj = System.Text.Json.JsonSerializer.Deserialize<CountryModel[]>(jsonResults);

    Console.WriteLine(cshrpObj.First().name);
}

【讨论】:

  • 谢谢你这么快回复!!不幸的是,我仍然收到错误 问题可能出在模型上吗??
  • @ChrisJ 该模型与 JSON 模式不一致。 name 不是字符串,而是它自己的模型。与tld 相同。您正在使用 C# 可空值,并且数据中缺少许多必填字段。你需要修复你的模型。从一对一的表示开始。
  • 我是 C# 的新手,所以有点困惑!!如何在我的模型中映射 JSON 中的一些键并忽略其余键?
  • 有关一对一的表示,请参见 Serge 的回答。
猜你喜欢
  • 2013-09-12
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多