2012-08-13 26 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