Categories
Geeky/Programming

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.

By Steve Novoselac

Director of Digital Technology @TrekBikes, Father, Musician, Cyclist, Homebrewer

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.