如何解决Newtonsoft.Json.JsonSerializationException:'无法反序列化当前JSON数组
我是API的新手,在过去的几天中,我一直在练习使用来自github等的预制API。现在,我决定尝试创建自己的冠状病毒追踪器应用程序(相当原始)。我遇到了标题为问题的问题,还没有在线找到解决方法。我想我尝试接收的JSON(https://api.covid19api.com/live/country/germany)是一个数组,我无法使其正常工作。我在非数组JSON(reddit's)上尝试过同样的事情,它的工作原理很吸引人。所有代码和类都粘贴在下面,感谢所有花时间阅读本文并决定提供帮助的人。
Newtonsoft.Json.JsonSerializationException:'无法将当前JSON数组(例如[1,2,3])反序列化为类型'Covid.Api.CovidStats',因为该类型需要JSON对象(例如{“ name”:“值”})以正确反序列化。 要解决此错误,可以将JSON更改为JSON对象(例如{“ name”:“ value”}),也可以将反序列化类型更改为数组,或者将实现集合接口的类型(例如ICollection,IList)更改为List,例如List从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; }
}
}
解决方法
API返回的不是单个对象的List
return JsonConvert.DeserializeObject<List<CovidStats>>(response);
更新:
为了完整性,您还需要更新方法的返回类型。完整代码如下:
public static async Task<List<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<List<CovidStats>>(response);
}
,
尝试一下
JsonConvert.DeserializeObject<CovidList>(response);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。