简体   繁体   English

ASP.Net Core 从外部 API 导入 JSON

[英]ASP.Net Core Import JSON from external API

I am new to both .NET Core home somebody can guide me through this.我是 .NET Core 主页的新手,有人可以指导我完成此操作。

I need to make a request to this url and save the data into database: url: https://covid19.mathdro.id/api我需要向这个 url 发出请求并将数据保存到数据库中: url: https://covid19.mathdro.id/api

JSON output looks like this: 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"}

Model: Totals型号:总计

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; }
}

My import model:我的进口型号:

client.BaseAddress = new Uri("https://covid19.mathdro.id/api");
var response = await client.GetAsync($"");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();

I am stuck from here and cant continue.我被困在这里,无法继续。 How do I fetch the data, I need only: confirmed, recovered, deaths and lastUpdate如何获取数据,我只需要:确认、恢复、死亡和上次更新

Pls.请。 anybody help here...任何人在这里帮助...

You need to cast JSON to a Class Object .您需要将JSON转换为Class Object You may get your data like this by using NewtonSoft.Json您可以使用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; }
}

You may fork or download this repo: https://github.com/fatihyildizhan/CoronaParser你可以 fork 或下载这个 repo: https : //github.com/fatihyildizhan/CoronaParser

Your modal should be你的模态应该是

public class Total
{
    public Confirmed confirmed { get; set; }
    public Recovered recovered { get; set; }
    public Deaths deaths { get; set; }
    public string dailySummary { get; set; }
    public DailyTimeSeries dailyTimeSeries { get; set; }
    public string image { get; set; }
    public string source { get; set; }
    public string countries { get; set; }
    public CountryDetail countryDetail { get; set; }
    public DateTime lastUpdate { get; set; }
}

public class Confirmed
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class Recovered
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class Deaths
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class DailyTimeSeries
{
    public string pattern { get; set; }
    public string example { get; set; }
}

public class CountryDetail
{
    public string pattern { get; set; }
    public string example { get; set; }
}

If stringResult has an actual value all you have to do is:如果stringResult有一个实际值,你所要做的就是:

JsonConvert.DeserializeObject<Total>(stringResult);

Also when in doubt about the modal you can always use http://json2csharp.com/此外,当对模态有疑问时,您可以随时使用http://json2csharp.com/

I suggest you to use JSon.NET aka Newtonsoft.我建议你使用 JSon.NET 又名 Newtonsoft。 You can add it from nuget package manager.您可以从 nuget 包管理器添加它。 Here is the code to map incoming json data to your custom class Total.这是将传入的 json 数据映射到自定义类 Total 的代码。 just add your class contructor which will take json data as argument which is typeof string, and I added one method to make code shorter只需添加您的类构造函数,它将 json 数据作为字符串类型的参数,并且我添加了一种方法来缩短代码

public class Total {

    public Total(string json) {
        JObject jObject = JObject.Parse(json);
        Confirmed = GetStringFromJToken(jObject, "confirmed");
        Recovered = GetStringFromJToken(jObject, "recovered");
        Deaths = GetStringFromJToken(jObject, "deaths");

        LastUpdated = (string)jObject["lastUpdate"];
    }

    private string GetStringFromJToken(JObject jObject, string key) {
        JToken keyToken = jObject[key];
        return (string)keyToken["value"];
    }

    [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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM