2012-08-13 27 views
2

我目前正在使用C#中的Facebook API,使用NewtonSoft JSON庫來消費所有返回的API數據。爲JSON訂閱源定義嵌套類的最佳方法

返回用戶頁面列表我發現自己在返回的JSON中爲屬性創建一個關閉類,以便序列化它。

現在我有這樣的:

public class FacebookPage 
    { 
     public string id { get; set; } 
     public string name { get; set; } 
     public string link { get; set; } 
     public string category { get; set; } 
     public bool is_published { get; set; } 
     public bool can_post { get; set; } 
     public int likes { get; set; } 
     public FacebookPageLocation location { get; set; } 
     public string phone { get; set; } 
     public int checkins { get; set; } 
     public string picture { get; set; } 
     public FacebookPageCover cover { get; set; } 
     public string website { get; set; } 
     public int talking_about_count { get; set; } 
     public string access_token { get; set; } 
    } 
    public class FacebookPageLocation 
    { 
     public decimal latitude { get; set; } 
     public decimal longitude { get; set; } 
    } 
    public class FacebookPageCover 
    { 
     public string cover_id { get; set; } 
     public string source { get; set; } 
     public int offset_y { get; set; } 
    } 

好像必須有一個更好的方式來做到這一點。我可以用Dictionary替換FacebookPageLocation,但我將如何去取代FacebookCoverPage?

理想情況下,我很想能夠宣稱它在一個不錯的嵌套形式,這樣

public class FacebookPage 
    { 
     id = string, 
     name = string. 
     link = string, 
     category = string, 
     is_published = bool, 
     can_post = bool, 
     likes = int, 
     location = 
     { 
      latitude = decimal, 
      longtitude = decimal 
     }, 
     phone = string, 
     checkins = int, 
     picture = string, 
     cover = 
     { 
      cover_id = string, 
      source = string, 
      offset_y = int 
     } 
     website = string, 
     talking_about_count = int, 
     access_token = string 
    } 

我知道這會在實踐中行不通,但有什麼,只是讓這些聲明種類更整齊?還是不必要?

回答

0

而不是宣佈很多類,我會使用dynamic。對於低於

{ 
    "name": "joe", 
    "id": 1151, 
    "location": { 
    "lat": 180.0, 
    "lng": -180.0 
    } 
} 

樣品JSON -

代碼將是

dynamic obj = JsonConvert.DeserializeObject(json); 
Console.WriteLine("{0} {1} {2}", obj.id, obj.name, obj.location.lat); 
+0

,看上去非常整潔。我想我會這樣做。謝謝! – roryok 2012-08-15 11:06:08