2012-09-13 47 views
-1

我是JSon的新手,特別是JSon.Net。我正嘗試使用Windows Phone上的LiveSDK,並且解析出JSon響應時出現問題。我正在嘗試讀取日曆信息,我無法解析它。下面是我下載Json和我的類定義的代碼。我在定義'用戶'的行上遇到異常。用JSon.Net反序列化LiveSDK日曆

void getCal_DownloadCompleted(object sender, LiveDownloadCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     { 
      using (var reader = new StreamReader(e.Result)) 
      { 
       var json = reader.ReadToEnd(); 
       var user = JsonConvert.DeserializeObject<Calendar>(json); 
      } 
     } 
    } 

[JsonObject(MemberSerialization.OptIn)] 
public class Calendar 
{  
    [JsonProperty(PropertyName="name")] 
    public string Name{get; set;} 
    [JsonProperty(PropertyName = "id")] 
    public string Id{get; set;} 
    [JsonProperty(PropertyName = "description")] 
    public string Description{get; set;} 
    [JsonProperty(PropertyName = "created_time")] 
    public string CreatedTime{get; set;} 
    [JsonProperty(PropertyName = "updated_time")] 
    public string UpdatedTime{get; set;} 
    [JsonProperty(PropertyName = "from")] 
    public object From{get; set;} 
    [JsonProperty(PropertyName = "is_default")] 
    public bool IsDefault{get; set;} 
    [JsonProperty(PropertyName = "subscription_location")] 
    public string SubscriptionLocation{get; set;} 
    [JsonProperty(PropertyName = "permissions")] 
    public string Permissions{get; set;} 
} 

JSON格式收到我的日曆類

{ 
    "data": [ 
    { 
    "id": "calendar.42d4dbc866f94c83849c88c6eb9985bc", 
    "name": "Birthday calendar", 
    "description": "If you have birthdays listed for your contacts, they'll appear on this calendar. You can add more birthdays, but you can't add other types of events.", 
    "created_time": "2011-08-05T19:41:04+0000", 
    "updated_time": "2011-08-05T19:41:04+0000", 
    "from": { 
     "name": null, 
     "id": null 
    }, 
    "is_default": false, 
    "subscription_location": null, 
    "permissions": "read" 
    },{ 
    ... 
    } 

] }

我用的是LiveSDK GetAsync(),所以我不會有運氣去與下載Async()代替。這種方法更好嗎?

謝謝

回答

0

您的序列化類似乎不匹配JSON。 JSON返回一個名爲data的屬性,該屬性是一個包含您定義的Calendar類的元素的數組。

嘗試增加一個新的類,如:

[JsonObject(MemberSerialization.OptIn)] 
public class AppointmentList 
{ 
    [JsonProperty(PropertyName="data")] 
    public List<Calendar> data {get; set;} 
} 

和反序列化,如:

var user = JsonConvert.DeserializeObject<AppointmentList>(json); 
+0

嘿非常感謝。我發誓我已經嘗試過,但沒有奏效,但現在一切都很順利。 – lucasbrendel