我有一个问题,即反序列化Json对象:
Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`1 [xxx.Models.FollowerResponseModel]',因为类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。 要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。 路径'用户',第2行,第10位。
{"result":{"status":200,"response":{"data":{"users":[
{"uin":223,"login":"tttttt","uin_follows":true,"follow_of_uin":false,"blocked":false},
{"uin":225,"login":"hggjhjj","uin_follows":false,"follow_of_uin":true,"blocked":true},
{"uin":226,"login":"testestefy","uin_follows":false,"follow_of_uin":false,"blocked":true}
],"version":"1"}}}}
My FollowersResponModel
public class FollowerResponseModel
{
[JsonProperty("users")]
public List<UserFollowersModel> Users { get; set; }
[JsonProperty("version")]
public int Version { get; set; }
}
public class UserFollowersModel
{
[JsonProperty("uin")]
public int Uin { get; set; }
[JsonProperty("login")]
public string Login { get; set; }
[JsonProperty("uin_follows")]
public bool UinFollows { get; set; }
[JsonProperty("follow_of_uin")]
public bool FollowOfUin { get; set; }
[JsonProperty("blocked")]
public bool Blocked { get; set; }
}
我的FollowersModel类应该如何?
我的方法GetFollowers ...
public async Task<List<FollowerModel>> GetFollowersBlockedList(int version)
{
var request = CreateHttpRequest(string.Format(FOLLOWERS_BLOCKED_URL), HttpMethod.Get, true);
var response = await CallRequestAsync(request, HttpContentType.ApplicationJson);
if (response == null) return null;
var stream = await response.Content.ReadAsStreamAsync();
var content = Tools.ConvertStreamToString(stream);
if (string.IsNullOrEmpty(content)) return null;
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(content);
if (response.IsSuccessStatusCode)
{
_log.MessageInDebug("OK");
var data = responseModel.Result.Response.Data.ToString();
var list = JsonConvert.DeserializeObject<List<FollowerResponseModel>>(data);
if (list == null || list.Count() == 0) return null;
return list.Select(x => new FollowerModel(x)).ToList();
}
return null;
}
答案 0 :(得分:2)
FollowerResponseModel
已包含List<User>
,因此您无需反序列化List<FollowerResponseModel>
var follow = JsonConvert.DeserializeObject<FollowerResponseModel>(data);
if (follow.Users == null || follow.Users.Count() == 0) return null;