If you use WebApi with the Asp.Net MVC framework you may not realize that there is some ‘magic’ that takes place under the hood to convert the over the wire data from Json into an object. You may not realize this because by default it ‘just works’, which is exactly what I want and what a framework should do.
However, if you are not using MVC and you are going to use WebApi endpoints from any other application you will have to handle this deserialization or transformation your self and we will find out that this is actually very easy.
If you are not familiar with the WebApi you can bounce over to a few of my prior posts about this topic:
When you set out to convert your Json data into an object you will want to do the following.
1) Include a reference to the System.Runtime.Serialization assembly in order to use the JsonValueExtension class.
2) Add a using statement for System.Runtime.Serialization.Json
3) Run the following in order to use the extension classes to turn your Json result into an object
response.Content
.ReadAsAsync()
.ContinueWith( readResult =>
{
var array = readResult.Result;
// How to transform the entire result from Json to an object
var episodes = array.ReadAsType<IList<Episode>>();
foreach ( var element in array )
{
// how to transform a single Json element to an object
var asEpisode = element.ReadAsType<Episode>();
}
} );
The magic in the code above is the usage of the ReadAsType extension method. This method will hide any of the complexities of turning the Json value into an object.
As you can see manually converting your Json into an object is simple and very straight forward.
Till next time,
Posted
03-01-2012 4:22 PM
by
Derik Whittaker