Facebook JSON string handling in C# MVC

340 views Asked by At

I trying to get the pictures along with likes from my Facebook fan page in MVC application. I am using Facebook C# SDK for this purpose. following is the code which returns the result in a JSON format.

var client = new FacebookClient();                
client.AppId= "your_access_token";
client.AppSecret = "your_App_Secret";
client.AccessToken = "your_access_token";
dynamic data= client.Get("FanPageName?fields=id,name,photos{name,source,likes.summary(true).filter(stream)}");

the above code returns an JSON and I stored it in a dynamic object named data. Now I want to iterate this JSON so that I can store the data in the database for further working.

I am confused here on how to iterate this dynamic object.

1

There are 1 answers

0
von v. On BEST ANSWER

Getting the info about the photos is as simple as doing:

foreach(dynamic photo in data.photos.data) {
   var url = photo.source.Value; // returns a string type
   var likes = ((IEnumerable)photo.likes.data).Cast<dynamic>()
        .Sum(x => x.total_count);
}

Take note of the Linq part as I was not sure if the likes.data returns an array with more than one item, it doesn't show in your comment. Although it doesn't make sense to have more than one item as a photo should (IMO) only have "one total count". If its guaranteed that it returns only one item then you can simply do a:

photo.likes.data[0].total_count.Value

But then again taking the Linq approach is the safer one.