[英]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.