2012-11-03 64 views
7
解析嵌套的JSON對象

我的JSON飼料已嵌套的對象是這樣的:與JSON.NET

{ 
"id": 1765116, 
"name": "StrozeR", 
"birth": "2009-08-12", 
"avatar": "http:\/\/static.erepublik.com\/uploads\/avatars\/Citizens\/2009\/08\/12\/f19db99e9baddad73981d214a6e576ef_100x100.jpg", 
"online": true, 
"alive": true, 
"ban": null, 
"level": 61, 
"experience": 183920, 
"strength": 25779.42, 
"rank": { 
    "points": 133687587, 
    "level": 63, 
    "image": "http:\/\/www.erepublik.com\/images\/modules\/ranks\/god_of_war_1.png", 
    "name": "God of War*" 
}, 
"elite_citizen": false, 
"national_rank": 6, 
"residence": { 
    "country": { 
     "id": 81, 
     "name": "Republic of China (Taiwan)", 
     "code": "TW" 
    }, 
    "region": { 
     "id": 484, 
     "name": "Hokkaido" 
    } 
} 
} 

和我的對象類是這樣的:

class Citizen 
{ 
    public class Rank 
    { 
     public int points { get; set; } 
     public int level { get; set; } 
     public string image { get; set; } 
     public string name { get; set; } 
    } 
    public class RootObject 
    { 
     public int id { get; set; } 
     public string name { get; set; } 
     public string avatar { get; set; } 
     public bool online { get; set; } 
     public bool alive { get; set; } 
     public string ban { get; set; } 
     public string birth { get; set; } 
     public int level { get; set; } 
     public int experience { get; set; } 
     public double strength { get; set; } 
     public List<Rank> rank { get; set; } 

    } 
} 

我嘗試解析我的JSON數據與下面的代碼

private async void getJSON() 
{ 
    var http = new HttpClient(); 
    http.MaxResponseContentBufferSize = Int32.MaxValue; 
    var response = await http.GetStringAsync(uri); 

    var rootObject = JsonConvert.DeserializeObject<Citizen.RootObject>(response); 
    uriTB.Text = rootObject.name; 
    responseDebug.Text = response; 
} 

,但我得到了以下錯誤:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Erepublik.Citizen+Rank]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 

我甚至無法解析主對象中的值。有任何解決這個問題的方法嗎?以及如何解析嵌套對象內的值?例如:「rank」中的「points」

+0

想知道你是如何將'residence','country','region'反序列化爲C#類的。我有類似的問題。你可以請張貼代碼嗎? – Venky

回答

19

與錯誤消息一樣,.NET類中的rank屬性爲List<Rank>,但在您的JSON中,它只是一個嵌套對象,而不是數組。將其更改爲Rank而不是List<Rank>

JSON(或任何Javascript,真的)中的數組都包含在[]中。 {}字符指定單個對象。 CLR類型必須大致匹配JSON類型才能反序列化。對象對象,數組到數組。

+0

謝謝。這是解決方案 – dum

+0

舊帖子,但今天它幫了我很多。節省時間 –

+0

那麼解決方案是什麼?你需要爲列表創建一個包裝?更清潔的解決方案 – sky91