[英]Cannot deserialize the current JSON object
我得到这个例外。 我不明白我该怎么办。 我用谷歌搜索了很多,但一无所获。
无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.ObjectModel.ObservableCollection`1[LU.FacebookStalker.StoreApp.ViewModel.PageLike]”,因为该类型需要一个 JSON 数组(例如 [1,2,3]) 以正确反序列化。
要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或列表)。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。
这是我的课:
public class PageLike
{
public string Id { get; set; }
public string Name { get; set; }
public string count { get; set; }
public string photoUrl { get; set; }
}
public class Hangout
{
public string Id { get; set; }
public string Name { get; set; }
public string photoUrl { get; set; }
public int count { get; set; }
}
public class Interaction
{
public string Id { get; set; }
public string Name { get; set; }
public string photoUrl { get; set; }
public int count { get; set; }
}
public class Place
{
public object Id { get; set; }
public string Name { get; set; }
public string photoUrl { get; set; }
public int count { get; set; }
}
public class HomeSummaryResult
{
public List<Hangout> hangouts { get; set; }
public List<Interaction> interactions { get; set; }
public List<PageLike> likes { get; set; }
public List<Place> places { get; set; }
}
public class RootObject
{
public HomeSummaryResult HomeSummaryResult { get; set; }
}
我正在调用这样的服务:
HttpClient client = new HttpClient();
string url = string.Format("");
HttpResponseMessage response = await client.GetAsync(url);
dynamic likesResult= await response.Content.ReadAsStringAsync();
var x = (JsonConvert.DeserializeObject<IDictionary<string, object>>(likesResult.ToString()))["HomeSummaryResult"];
likesList = JsonConvert.DeserializeObject<ObservableCollection<PageLike>>(x.ToString());
我的 JSON 是:
{
"HomeSummaryResult": {
"hangouts": [
{
"Id": "112",
"Name": "Mohsin",
"photoUrl": "graph.facebook.com\/112\/picture",
"count": 12
},
{
"Id": "103",
"Name": "Khan",
"photoUrl": "graph.facebook.com\/103\/picture",
"count": 11
}
],
"interactions": [
{
"Id": "724",
"Name": "Jawad Shareef",
"photoUrl": "graph.facebook.com\/724\/picture",
"count": 482
},
{
"Id": "583",
"Name": "Ahsan Aziz Abbasi",
"photoUrl": "graph.facebook.com\/583\/picture",
"count": 228
}
],
"likes": [
{
"Id": "122",
"Name": "Community",
"photoUrl": "graph.facebook.com\/122\/picture",
"count": 324
},
{
"Id": "110",
"Name": "Musician\/band",
"photoUrl": "graph.facebook.com\/110\/picture",
"count": 119
}
],
"places": [
{
"Id": null,
"Name": "Local business",
"photoUrl": "graph.facebook.com\/\/picture",
"count": 69
},
{
"Id": null,
"Name": "City",
"photoUrl": "graph.facebook.com\/\/picture",
"count": 43
}
]
}
}
所以这就是答案。 我自己解决了。
我刚刚添加了["likes"]
代码是:
var x = (JsonConvert.DeserializeObject<IDictionary<string, object>>(likesResult.ToString()))["HomeSummaryResult"]["likes"];
因为 json 在数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.