正文如下:
{
"_total": 3,
"users": [
{
"username": "person1",
"points": 3
},
{
"username": "person2",
"points": 2
},
{
"username": "person3",
"points": 1
}
]
}
代码:
public class UserData
{
public string username { get; set; }
public int points { get; set; }
}
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<UserData>>(body);
foreach (UserData userdata in data)
{
Debug.Log(userdata.username + ": " + userdata.points);
}
}
错误:
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[UserData]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
要修复此错误,要么将JSON更改为JSON数组(例如[1,2,3]),要么更改反序列化类型,使其成为可以从JSON对象反序列化的普通。net类型(例如,不是像整数这样的原始类型,也不是像数组或列表这样的集合类型)。还可以将JsonObjectAttribute添加到类型中,以强制它从JSON对象进行反序列化。
类与JSON结构不匹配,因此您将获得JsonSerializationException
Exception。
你的模型应该看起来像这样:
public class RootClass
{
public int _total { get; set; }
public List<User> users { get; set; }
}
public class User
{
public string username { get; set; }
public int points { get; set; }
}
你可以这样做:
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<RootClass>(body);
foreach (User userdata in data.users)
{
Debug.Log(userdata.username + ": " + userdata.points);
}
}
您可以先解析json字符串,然后将其反序列化为UserData列表
var data = JObject.Parse(body)["users"].ToObject<List<UserData>>();