Facebook fixed the /likes
in Graph API. /likes
now returns the complete list of user's that liked a particular object in the graph (Photos, Albums, etc). In before, it returns only 3 - 5 users.
My question is, how do you count the total number of "likes" withou开发者_开发知识库t parsing the entire JSON and getting the element count? I'm only interested in the "likes" count; I'm not interested in the users who gave the likes.
It seems a little expensive to get the entire JSON dataset just to count.
EG: https://graph.facebook.com/161820597180936/likes
This photo has like 1,000+ likes.
Seeing as the string is JSON, why not convert it into a standard .net object, and use the .Count on the array that it creates. Then cache this information for 15 or more minutes (depending on stale you want your info).
The method above is quite heavy handed as you are essentially going to search a string an unknown number of times, to return an index, to compare it to an int, to add up another index and so on. And the C# above doesn't work (assuming it is C# that you are demoing).
Use something like this instead:
public static T FromJson<T>(this string s)
{
var ser = new System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer();
return ser.Deserialize<T>(s);
}
where this method is an extension method, that takes properly formatted JSON string and converts it to the object T e.g.
var result = // call facebook here and get your response string
List<FacebookLikes> likes = result.FromJson <List<FacebookLikes>>();
Response.Write(likes.Count.ToString());
// now cache the likes somewhere, and get from cache next time.
Am not sure on the performance of this, not done any testing, but to me it looks a lot tidier and a lot more readable. And seeing as you are caching the data, then I'd go with the readable over the previous method.
Why is it expensive to parse the entire dataset? This should take milliseconds:
public static int CountLikes(string dataSet)
{
int i = 0;
int j = 0;
while ((i = dataSet.IndexOf('"id":', i)) != -1)
{
i += 5;
j++;
}
return j;
}
You can also append the parameter limit=# such as:
https://graph.facebook.com/161820597180936/likes?limit=1000
精彩评论