【发布时间】: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