2014-07-15 56 views
0

我需要反序列化類型Dictionary的JSON字典到列表(List),我正在使用JSON.Net來達到此目的。當然,它是一個了不起的圖書館,它只是我被卡住了!反序列化一個JSON字典<int,CustomType>到列表<CustomType>

我訂閱一些API的響應正如你可以看到下面:

"team_details": { 
       "0": { 
        "index": 1, 
        "team_id": "1..", 
        "team_name": "Research Team", 
        "team_url": "...", 
        "role": "Administrator" 
       }, 
       "1": { 
        "index": 2, 
        "team_id": "2..", 
        "team_name": "WB Team", 
        "team_url": "...", 
        "role": "User" 
       } 
} 

我需要用這個將其轉換爲List<Team>,隊員:

Class Teams{ 

public int Index{get;set;} 

public String TeamName{get;set;} 

... 
} 
+0

首先,你要確保你的[JSON是有效的(http://jsonlint.com/)? – mason

+0

這個JSON是有效的,它只是有點尷尬,列表不是作爲一個數組存儲的,而是作爲鍵值對象,其中鍵是索引。 – Davio

+0

是的,它是有效的,它的內部讓我們說一個JsON字典。 – bhuvin

回答

2

以最簡單的方式這是爲了反序列化爲Dictionary<string, Team>,然後在需要時使用dictionary.Values.ToList()將值獲取到列表中。

但是,如果您確實想在您的類定義中使用List<Team>,則可以使用自定義JsonConverter在反序列化期間執行轉換。

public class TeamListConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     return (objectType == typeof(List<Team>)); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     JToken token = JToken.Load(reader); 
     return token.Values().Select(v => v.ToObject<Team>()).ToList(); 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 

演示:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string json = @" 
     { 
      ""team_details"": { 
       ""0"": { 
        ""index"": 1, 
        ""team_id"": ""1.."", 
        ""team_name"": ""Research Team"", 
        ""team_url"": ""..."", 
        ""role"": ""Administrator"" 
       }, 
       ""1"": { 
        ""index"": 2, 
        ""team_id"": ""2.."", 
        ""team_name"": ""WB Team"", 
        ""team_url"": ""..."", 
        ""role"": ""User"" 
       } 
      } 
     }"; 

     RootObject root = JsonConvert.DeserializeObject<RootObject>(json); 

     foreach (Team team in root.Teams) 
     { 
      Console.WriteLine(team.TeamName); 
     } 
    } 
} 

public class RootObject 
{ 
    [JsonProperty("team_details")] 
    [JsonConverter(typeof(TeamListConverter))] 
    public List<Team> Teams { get; set; } 
} 

public class Team 
{ 
    [JsonProperty("index")] 
    public int Index { get; set; } 
    [JsonProperty("team_id")] 
    public string TeamId { get; set; } 
    [JsonProperty("team_name")] 
    public string TeamName { get; set; } 
    [JsonProperty("team_url")] 
    public string TeamUrl { get; set; } 
    [JsonProperty("role")] 
    public string Role { get; set; } 
} 

輸出:

Research Team 
WB Team 
+0

感謝Brian +1! – bhuvin

+0

沒問題;樂意效勞。 –

相關問題