我是 .NET Core 家庭的新手,有人可以指导我完成此操作。
我需要向这个 url 发出请求并将数据保存到数据库中: 网址: https://covid19.mathdro.id/api
JSON 输出如下所示:
{"confirmed":{"value":303001,"detail":"https://covid19.mathdro.id/api/confirmed"},"recovered":{"value":91669,"detail":"https://covid19.mathdro.id/api/recovered"},"deaths":{"value":12762,"detail":"https://covid19.mathdro.id/api/deaths"},"dailySummary":"https://covid19.mathdro.id/api/daily","dailyTimeSeries":{"pattern":"https://covid19.mathdro.id/api/daily/[dateString]","example":"https://covid19.mathdro.id/api/daily/2-14-2020"},"image":"https://covid19.mathdro.id/api/og","source":"https://github.com/mathdroid/covid19","countries":"https://covid19.mathdro.id/api/countries","countryDetail":{"pattern":"https://covid19.mathdro.id/api/countries/[country]","example":"https://covid19.mathdro.id/api/countries/USA"},"lastUpdate":"2020-03-21T20:13:21.000Z"}
型号:总计
public class Total
{
[Key]
public int Id { get; set; }
[Column(TypeName = "int")]
[Required]
public string Confirmed { get; set; }
[Column(TypeName = "int")]
[Required]
public string Recovered { get; set; }
[Column(TypeName = "int")]
[Required]
public string Deaths { get; set; }
[Column(TypeName = "datetime2")]
[Required]
public string LastUpdated { get; set; }
}
我的导入模型:
client.BaseAddress = new Uri("https://covid19.mathdro.id/api");
var response = await client.GetAsync($"");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
我从这里卡住了,无法继续。 如何获取数据,我只需要:已确认、已恢复、死亡和 lastUpdate
请。任何人都可以在这里帮助...
最佳答案
您需要将 JSON
转换为 Class Object
。您可以使用 NewtonSoft.Json
using (var client = new HttpClient())
{
string url = string.Format("https://covid19.mathdro.id/api");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}
public class CovidResult
{
[JsonProperty("confirmed")]
public ValueModel Confirmed { get; set; }
[JsonProperty("recovered")]
public ValueModel Recovered { get; set; }
[JsonProperty("deaths")]
public ValueModel Deaths { get; set; }
}
public class ValueModel
{
[JsonProperty("value")]
public int Value { get; set; }
}
您可以 fork 或下载此 repo: https://github.com/fatihyildizhan/CoronaParser
关于c# - ASP.Net Core 从外部 API 导入 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793702/