2014-03-06 99 views
1

第三方的API返回JSON的格式如下JSON結構問題

{ 
"group1": { 
    "Colour": "Blue", 
    "Name": "Dave" 
}, 
"group2": { 
    "Colour": "Red", 
    "Name": "Karen" 
}, 
"group3": { 
    "Colour": "Green", 
    "Name": "Ryan" 
} 
} 

試圖反序列化使用JSON.NET的JSON當我發現外「groupX」標識有問題的。

有沒有人知道最好解析這種格式的JSON?

回答

0
{ 
    "employees": [ 
     { "first-name":"John" , "last-name":"Doe" }, 
     { "first-name":"Anna" , "last-name":"Smith" }, 
     { "first-name":"Peter" , "last-name":"Jones" } 
    ] 
} 
+0

感謝@AmalaBalaji但不幸的是我無法改變的JSON – jjc99

+0

的這不回答這個問題,格式爲「如何最好地解析JSON的這種格式?」 –

0

您的JSON是正確的。 如果土特產品要檢查除了下面網址JSONlint

0

使用定義一個類Group這樣的:

class Group 
{ 
    public string Colour { get; set; } 
    public string Name { get; set; } 
} 

然後你就可以反序列化這樣的:

var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json); 

這裏有一個快速演示:

string json = @" 
{ 
""group1"": { 
    ""Colour"": ""Blue"", 
    ""Name"": ""Dave"" 
}, 
""group2"": { 
    ""Colour"": ""Red"", 
    ""Name"": ""Karen"" 
}, 
""group3"": { 
    ""Colour"": ""Green"", 
    ""Name"": ""Ryan"" 
} 
}"; 

var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json); 
foreach (var kvp in dict) 
{ 
    Console.WriteLine(kvp.Key); 
    Group group = kvp.Value; 
    Console.WriteLine(" Colour: " + group.Colour); 
    Console.WriteLine(" Name: " + group.Name); 
} 

產量:

group1 
    Colour: Blue 
    Name: Dave 
group2 
    Colour: Red 
    Name: Karen 
group3 
    Colour: Green 
    Name: Ryan