[英]C# throws Unhandled exception error
尝试执行以下代码时, Unhandled exception error
:
class JsonData
{
public static async Task RefreshDataAsync()
{
Console.WriteLine("Tes2t");
var uri = new Uri("https://api.myjson.com/bins/****b");
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
//This line throws the error
var Items = JsonConvert.DeserializeObject<List<Rootobject>>(content);
Console.WriteLine(content);
}
}
}
根对象:
public class Rootobject
{
public int wantedDegree { get; set; }
public int currentDegree { get; set; }
}
我的JSON数组:
{
"wantedDegree": 22,
"currentDegree": 20
}
我还按照建议使用了JSON到C#的转换器,但它给了我相同的RootObject。
错误:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Smart_Thermometer.Rootobject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
12-08 01:10:02.660 I/mono-stdout(11816):
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'wantedDegree', line 1, position 16.
就像其他人在评论中说的那样,您的JSON与您要反序列化的类型不匹配。
如果您的JSON是正确的,那么您想将其反序列化为单个对象:
var item = JsonConvert.DeserialiseObject<Rootobject>(content);
否则,如果您期望这些序列,那么您的JSON应该类似于:
[{
"wantedDegree": 22,
"currentDegree": 20
}, {
"wantedDegree": 100,
"currentDegree": 90
}, {
"wantedDegree": 5,
"currentDegree": 3
}]
根据异常消息:
要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型。
如果要反序列化数组,则必须提供一个数组,如下所示:
[
{
"wantedDegree": 22,
"currentDegree": 20
}
]
或将通用类型参数更改为简单的.NET类型而不是集合:
var Items = JsonConvert.DeserializeObject<Rootobject>(content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.