我目前正在使用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
}
我意识到这在实践中行不通,但是有什么东西可以让声明这些类更整洁吗?还是不必要的?
我会使用 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);