Deserialize JSON response into a Dynamic Object

Here I will discuss the approach I included in my APIMASH Starter Kit to deserialize a JSON response into a dynamic object.


Before going into specifics of how I use dynamic objects in my APIMASH Starter Kit, let me provide some background information.  When you compile your code, the compiler checks if there’s an existing type defining the methods and properties of your objects, if this check fails, you will get a compilation error. In contrast, when you use dynamic objects, the compiler bypasses this check and instead collects information (metadata) for the purpose of resolving the properties and methods of the dynamic objects at runtime.  What tells the compiler to bypass this check is the dynamic keyword. 


You can create custom types that benefit from the run-time dynamic functionality. The key is the implementation of the standard Dynamic Language Runtime (DLR) interface, IDynamicMetaObjectProvider. To help you with this, you can inherit from the DynamicObject class and override the appropriate members according to your desired behavior. 


For my Starter Kit, I wanted to use dynamic objects to avoid having to create, and therefore maintain, strongly typed classes representing the entire data model of a third party API. Furthermore, the Eventbrite API (The API I am using in my Starter Kit), returns a complex object structure which provides very detailed information, which is great in most cases, but for the purpose of my Starter Kit, I wasn’t’ going to need most of it.  Another point to consider is that dynamic objects could help you preventing having to change your code if changes such as adding new fields occur in the source API. In other words, you App is less coupled to the source API.


Instead of creating a dynamic type from the grounds up, I’m using the ExpandoObject, which provides the functionality I need and works with the JSON serializer I am leveraging. 


In the following snipped of code, I show how I am invoking the API using the methods from my previous blog post

var longitude = "MY LONGITUDE";
var latitude = "MY LATITUDE";
var category = "MY CATEGORY";

dynamic apiDTO = await ApiMashInvoke.InvokeAsync<ExpandoObject>(
                                       new KeyValuePair<string, string>("app_key", ApiResources.APP_KEY),
                                       new KeyValuePair<string, string>("longitude", longitude),
                                       new KeyValuePair<string, string>("latitude", latitude),
                                       new KeyValuePair<string, string>("within", "1"),
                                       new KeyValuePair<string, string>("category", category)


The result from the API call is dynamic Data Transfer Object, from where I can map the appropriate data to the View Models of my Starter Kit.


In my next post, I will discuss the mapping process as well as the View Models of my application.

No Comments

Post Reply