【发布时间】:2020-09-05 23:25:15
【问题描述】:
我是 API 新手,在过去的几天里,我一直在练习使用来自 github 等的预制的。现在我决定尝试创建自己的冠状病毒追踪器应用程序(非常原创)。我遇到了标题问题,并没有在网上找到如何解决它的解决方案。我猜我试图接收的 JSON (https://api.covid19api.com/live/country/germany) 是一个数组,我无法让它工作。我在非数组 JSON(reddit's)上尝试了同样的事情,它就像一个魅力。所有代码和类都粘贴在下面,感谢任何花时间阅读本文并决定提供帮助的人。
Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'Covid.Api.CovidStats',因为该类型需要 JSON 对象(例如 {"name":" value"}) 以正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。 JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组中反序列化。 路径'',第 1 行,位置 1。'
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Covid.Api
{
public class CovidClient
{
public async Task<CovidStats> GetByCountryLiveStats(string country,DateTime startDate,DateTime endDate)
{
var url = $"https://api.covid19api.com/country/{country}/status/confirmed/live?from={startDate}&to={endDate}";
var client = new HttpClient();
var response = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject<CovidStats>(response);
}
}
public class CovidStats
{
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Cases")]
public int Cases { get; set; }
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Date")]
public DateTime date { get; set; }
}
public class CovidList
{
List<CovidStats> lista { get; set; }
}
}
【问题讨论】: