2

我目前正在使用 c# 中的 Facebook API,使用 NewtonSoft JSON 库来使用所有返回的 API 数据。

返回用户页面列表时,我发现自己为返回的 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
    }

我意识到这在实践中是行不通的,但是有什么东西可以让声明这些类更整洁吗?还是不必要的?

4

1 回答 1

0

我不会声明很多类,而是使用dynamic. 对于下面的示例 json

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

-

代码将是

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine("{0} {1} {2}", obj.id, obj.name, obj.location.lat);
于 2012-08-13T14:46:53.580 回答