我目前正在使用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
}
我意识到这在实践中不起作用,但是有什么东西可以宣布这些类更整洁吗?还是不必要的?
答案 0 :(得分: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);