Using JSON in Facebook C# API without the need for dynamic

If you happen to look at a lot of the examples that the Facebook C# API uses, you’ll notice a some of examples utilize the dynamic keyword (another example). This makes sense because it’s supported by the C# language and is a very nice feature to use.

In case you didn’t know, dynamic defers any type checking until runtime; this means that you can dynamically refer to a type, without intellisense in the Visual Studio designer, only to be met with type checking at runtime. If you call a property or method that doesn’t exist on an object reference, for instance, an exception will be thrown at runtime, but the code will still compile.

Recently, I’ve been using Xamarin Android and iOS frameworks for developing mobile applications, and I stumbled upon a limitation: dynamic is not supported, which this code broke when I tried to port it from Android to iOS:

var attributes = fb.Get<IDictionary<string, object>>("/me?fields=id,name,first_name,last_name,picture");
.
.

if (attributes.ContainsKey ("picture"))
{
   dynamic pictureObj = attributes["picture"];
   if (pictureObj != null) {
      dynamic data = pictureObj ["data"];

      if (data != null)
         pictureUrl = data ["url"].ToString ();
   }
}

The facebook API returns the current user’s picture as a complex object, that is represented by the following:

picture: { data: { url: "urltoimage" } }

That’s not all that comes along, but is mostly what we care about for this discussion. Anyway, to parse it using dynamic created a problem in iOS, as this generated errors. The solution was to use the following instead:

if (attributes.ContainsKey ("picture"))
{
   var pictureObj = attributes["picture"] as Facebook.JsonObject;
   if (pictureObj != null) {
      var data = pictureObj ["data"] as Facebook.JsonObject;

      if (data != null)
         pictureUrl = data ["url"].ToString ();
   }
}

The Facebook C# team does not want you using JsonObject directly, which is why it doesn’t show up in intellisense, but it is supported, and is the only representation of an object that allows you to easily extract the URL from the picture object, without a lot of reflection. This then works seamlessly in both Android and iOS.

Advertisements

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