2013-02-28 81 views
-1

我試圖反序列化JSON之後到一個對象在我贏8應用:反序列化JSON與JSON.NET在Windows 8 Store應用

{ 
"success":true, 
"pharmacies":[ 
{ 
"name":"Test Pharmacy", 
"phone":null, 
"description":"sample description", 
"pharmacyid":"1234567", 
"pic":"/1341864197.png", 
"address":"211 Warren St., #205", 
"city":"Newark", 
"state":"NJ", 
"zipcode":"07103", 
"delivery":true, 
"dob_check":false, 
"name_check":false, 
"can_pickup":true, 
"barcode_template":"9999999XX" 
} 
] 
} 

這是我使用的模型:

public class PharmacyList 
{ 
    public List<Pharmacy> pharmacies { get; set; } 
} 
public class Pharmacy 
{ 
    public string pharmacyid { get; set; } 
    public string name { get; set; } 
    public string phone { get; set; } 


} 

這裏是我使用的代碼反序列

json = await results.Content.ReadAsStringAsync(); 
List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json); 

,我發現了以下異常:

:無法反序列化當前的JSON對象(例如, {「name」:「value」})類型爲'System.Collections.Generic.List`1 [PharmacyHC.Models.PharmacyList]',因爲該類型需要JSON數組(例如[1,2,3])來正確地反序列化。

我想反序列化爲錯誤的類型,還是應該格式化JSON,因爲它以不同的方式返回API?

+0

要誰下投這個職位的人:請留下一個原因,這是不夠的。 – Subby 2013-12-11 09:47:14

回答

0

我剛剛意識到我犯的愚蠢錯誤。 p應該被聲明爲類型PharmacyList而不是列表對象,因爲PharmacyList的類聲明已經包含List對象。

List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json); 

它應該是

PharmacyList p = JsonConvert.DeserializeObject<PharmacyList>(json);