c# - ASP.Net Core 从外部 API 导入 JSON

标签 c# json asp.net-core asp.net-core-webapi

我是 .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/

相关文章:

c# - 在 EF Core 中使用 UserManager 进行预加载

c# - DataSet.Copy 与 Dataset.Clone

排序 GridView 时 C# 无限循环

c# - 从 ASP.Net 用户控制事件调用页面上的 javascript

json - 尝试使用 curl 创建 repo 时,Github 返回 "Problems parsing JSON"

php - 添加 eventNotification 后记录 INVALID_REQUEST_BODY

javascript - d3.js 中的简单条形图

C# ComboBox 选定值从数据库返回 Null、Item 和 Value

c# - Quartz.Net 依赖注入(inject) .Net Core

c# - 继承 .NET Core 中的 appsettings.json 设置