我尝试使用REST Sharp通过API访问COVID19 JSON格式的数据,但在尝试反序列化时遇到错误。我是Rest Sharp的新手。不确定我错过了什么。
C#代码公共无效getCOVIDData() {
var client = new RestClient("https://covid-19-data.p.rapidapi.com/country?format=json&name=France");
var request = new RestRequest(Method.GET);
request.AddHeader("x-rapidapi-host", "covid-19-data.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", constants.apiKey);
IRestResponse<COVID_Data.RootObject> response = client.Execute<COVID_Data.RootObject>(request);
//the below line returns a JSON object without a problem
string covidData = JsonConvert.DeserializeObject(response.Content).ToString();
//this line returns NewtonSoft.JSON.JSON.SerializationException error (see screen shot)
COVID_Data.RootObject data = JsonConvert.DeserializeObject<COVID_Data.RootObject>(response.Content);
}
返回的对象为
{“国家”:“法国”,“代码”:"FR",“已确认”:181575,“已恢复”:63354,“危急”:1794,“死亡”:28239,“纬度”:46.227638,“经度”:2.213749,"lastChange":"2020-05-20T14:53:01-04:00","lastUpdate":"2020-05-21T10:15:02-04:00“}
当我尝试创建一个COVID_Data类并反序列化为一个RootObject时,我得到了下面的异常错误。
JSON
COVID_Class的设置如下所示。
公共类COVID_Data {
public class RootObject
{
[JsonProperty("country")]
public string country { get; set; }
[JsonProperty("code")]
public string code { get; set; }
[JsonProperty("confirmed")]
public int confirmed { get; set; }
[JsonProperty("recovered")]
public int recovered { get; set; }
[JsonProperty("critical")]
public int critical { get; set; }
[JsonProperty("deaths")]
public int deaths { get; set; }
[JsonProperty("latitude")]
public double latitude { get; set; }
[JsonProperty("longitude")]
public double longitude { get; set; }
[JsonProperty("lastChange")]
public string lastChange { get; set; }
[JsonProperty("lastUpdate")]
public string lastUpdate { get; set; }
}
}
发布于 2020-05-24 06:44:36
我能够通过使用JArray然后迭代JTokens来让它工作。
JArray数组= JArray.Parse(response.Content);
string outputText = "";
string twoNewLines = Environment.NewLine + Environment.NewLine;
foreach (JToken pair in array)
outputText = "Country: " + array[0]["country"] + twoNewLines +
"Confirmed: " + array[0]["confirmed"] + twoNewLines +
"Recovered: " + array[0]["recovered"] + twoNewLines +
"Critical: " + array[0]["critical"] + twoNewLines +
"Deaths: " + array[0]["deaths"] + twoNewLines +
"Last Update: " + array[0]["lastUpdate"];
1中的outputText
https://stackoverflow.com/questions/61937685
复制相似问题