【发布时间】:2018-02-01 15:03:50
【问题描述】:
我在反序列化 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 对象反序列化的数组或列表。 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;
}
【问题讨论】:
-
响应中的 json 是什么样的?确保 users 是一个数组。
-
json 是什么样的?您正在尝试反序列化为 List
,但它告诉您 json 是单个对象 -
对不起,我忘了添加:{"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":真,“阻塞”:真},{“uin”:226,“登录”:“testestefy”,“uin_follows”:假,“follow_of_uin”:假,“阻塞”:真}],“版本”:“1 "}}}}
-
您正在尝试反序列化数据,这是一个对象。 Data["users"] 是一个数组。
-
@Jason 你能告诉我它应该是什么样子吗?