【发布时间】:2021-11-22 17:38:35
【问题描述】:
我想从我的 ASP.Net Core 应用程序中调用 API,但响应格式不是很好:
[
{
page: 1,
pages: 1,
per_page: 50,
total: 2,
sourceid: "2",
sourcename: "World Development Indicators",
lastupdated: "2021-10-28"
},
[
{
indicator: {
id: "NY.GDP.PCAP.KD.ZG",
value: "GDP per capita growth (annual %)"
},
country: {
id: "CA",
value: "Canada"
},
countryiso3code: "CAN",
date: "2020",
value: -6.33904652535297,
unit: "",
obs_status: "",
decimal: 1
},
{
indicator: {
id: "NY.GDP.PCAP.KD.ZG",
value: "GDP per capita growth (annual %)"
},
country: {
id: "CA",
value: "Canada"
},
countryiso3code: "CAN",
date: "2019",
value: 0.43021113414872,
unit: "",
obs_status: "",
decimal: 1
}
]
]
这里是 API 网址: https://api.worldbank.org/v2/country/can/indicator/NY.GDP.PCAP.KD.ZG?format=json&mrv=2
我已经为响应键入了这些类:
public class WorldBankApiResponseGlobal
{
public int Page { get; set; }
public int Pages { get; set; }
public int Per_Page { get; set; }
public int Total { get; set; }
public string Sourceid { get; set; }
public string Sourcename { get; set; }
}
public class WorldBankApiIdValue
{
public string Id { get; set; }
public string Value { get; set; }
}
public class WorldBankApiResponse
{
public WorldBankApiIdValue Indicator { get; set; }
public WorldBankApiIdValue Country { get; set; }
public int Value { get; set; }
public string Date { get; set; }
public string Countryiso3code { get; set; }
}
但是,由于响应没有对象的属性值(即:[{},[]] 而不是 ["data": {}, "indicators": []],我不知道如何正确反序列化 API 调用响应...
通常,我会这样做:
var response = await _client.GetFromJsonAsync<List<WorldBankApiResponseGlobal>>(worldBankApiUrl);
但是有谁知道我会如何处理这种响应类型?
【问题讨论】:
-
dotnetfiddle.net/3Rqnya,这是一个简单的解决方案。这是来自 app.quicktype.io/?l=csharp 的美化副本
标签: c# json .net-core deserialization httpclient