2014-08-28 346 views
-1

我有一個從API調用返回了以下JSON:轉換JObject到custome實體 - C#

{ 
    "Success": true, 
    "Message": null, 
    "Nodes": [ 
     { 
      "Title": "Title 1", 
      "Link": "http://www.google.com", 
      "Description": null, 
      "PubDate": "2014-06-19T13:32:00-07:00" 
     }, 
     { 
      "Title": "Title 2", 
      "Link": "http://www.bing.com", 
      "Description": null, 
      "PubDate": "2014-06-26T13:14:00-07:00" 
     }, 

    ] 
} 

我有以下對象到JSON轉換爲自定義對象

[JsonObject(MemberSerialization.OptIn)] 
public class MyApiResponse 
{ 
    [JsonProperty(PropertyName = "Success")] 
    public bool Success { get; set; } 

    [JsonProperty(PropertyName = "Message")] 
    public string Message { get; set; } 

    [JsonProperty(PropertyName = "Nodes")] 
    public IEnumerable<object> Nodes { get; set; } 
} 

我能夠執行以下代碼行以反序列化到MyApiResponse對象。

MyApiResponse response = JsonConvert.DeserializeObject<MyApiResponse>(json); 

我想通過MyApiResponse對象可以序列化他們到另一個物體的Nodes財產循環。當我嘗試下面的代碼片段,它拋出一個錯誤:

foreach(var item in response.Nodes) 
{ 
    MyObject obj = JsonConvert.DeserializeObject<MyObject>(item.ToString()); 
} 

什麼我需要做的item轉換成我MyObjectforeach循環?

+0

所以你的問題是,爲什麼它拋出的錯誤?如果是,請提供錯誤消息。或者你的問題是:我需要做什麼來將項目轉換成foreach循環中的MyObject?如果這樣,因爲你將它聲明爲MyApiResponse類中的節點,所以如果你想改變爲別的東西,肯定需要將其轉換爲 – 2014-08-28 01:12:27

+0

@ah_hau - 當我嘗試循環遍歷時,它看起來像是拋出HTTP 500錯誤'Nodes'屬性將它們轉換爲'MyObject'數據類型 – 2014-08-28 01:42:05

+0

可以發佈更多代碼嗎? HTTP 500內部服務器錯誤是通用服務器錯誤,如果您已經收到您的回覆,爲什麼它仍然調用Web功能?你的JsonConvert調用了在線託管的第三方轉換器嗎? – 2014-08-28 01:47:08

回答

1

你只需要定義一個類來表示一個節點,然後更改Nodes財產在你MyApiResponse類是List<Node>(或IEnumerable<Node>,如果你喜歡),而不是IEnumerable<object>。當您撥打JsonConvert.DeserializeObject<MyApiResponse>(json)時,整個JSON響應會一次反序列化。應該不需要單獨對每個子項目進行反序列化。

[JsonObject(MemberSerialization.OptIn)] 
public class Node 
{ 
    [JsonProperty(PropertyName = "Title")] 
    public string Title { get; set; } 

    [JsonProperty(PropertyName = "Link")] 
    public string Link { get; set; } 

    [JsonProperty(PropertyName = "Description")] 
    public string Description { get; set; } 

    [JsonProperty(PropertyName = "PubDate")] 
    public DateTime PubDate { get; set; } 
} 

[JsonObject(MemberSerialization.OptIn)] 
public class MyApiResponse 
{ 
    [JsonProperty(PropertyName = "Success")] 
    public bool Success { get; set; } 

    [JsonProperty(PropertyName = "Message")] 
    public string Message { get; set; } 

    [JsonProperty(PropertyName = "Nodes")] 
    public List<Node> Nodes { get; set; } 
} 

然後:

MyApiResponse response = JsonConvert.DeserializeObject<MyApiResponse>(json); 

foreach (Node node in response.Nodes) 
{ 
    Console.WriteLine(node.Title); 
}