Facebook Graph API – Getting Friends and Gender in C#

I recently blogged about the Facebook Graph API and if you have the Facebook C# SDK you can start making applications.

After I had my Facebook app set up, I started making a C# Console application to just get my friends and see what I could do. Here is a snippet to get my friends and their gender.

       string token = ;

            Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);

            JSONObject f = api.Get("/me/friends");

            KeyValuePair friends = f.Dictionary.ElementAt(0);


            for (int i = 0; i < friends.Value.Array.Count(); i++)
            {
   
                Console.WriteLine("Friend #" + i.ToString());

                JSONObject friend = api.Get("/" + friends.Value.Array[i].Dictionary["id"].String);

                Console.WriteLine(friend.Dictionary["name"].String);

                try
                {
                    Console.WriteLine(friend.Dictionary["gender"].String);
                }
                catch(System.Collections.Generic.KeyNotFoundException knfe)
                {
                    Console.WriteLine("No Gender Specified");
                }

                Console.WriteLine();
            }


            Console.ReadLine();

There is a probably a better way to do this, but getting the JSONObject back and then getting the values you get back from that, I just kind of brute forced it. Also, handling friends that don’t have information set, the quick and dirty way was to just catch the exception. I know there has to be a better way but for now it works.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s