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.
In the following snipped of code, I show how I am invoking the API using the methods from my previous blog post
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.