Derik Whittaker

Syndication

News


WebApi and Json Deserialization into an object model

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
Filed under: ,

[Advertisement]

Comments

Jarrod wrote re: WebApi and Json Deserialization into an object model
on 03-02-2012 12:11 PM

And this will work no matter what serializer is used on the server side?  i.e. DataContractJsonSerializer, JSON.NET or ServiceStack.Text

Sean wrote re: WebApi and Json Deserialization into an object model
on 03-02-2012 6:31 PM

@Jarrod --  for those you can just do this:

// JSON.Net

var episodes = JsonConvert.DeserializeObject<List<Episode>>(readResult.Result);

//ServiceStack.Text

var episodes = JsonSerializer.DeserializeFromString<List<Episode>>(readResult.Result);

Works like a charm, no need to read each element again and either deserialization method works regardless of the serialization method (I mixed and matched).  

foreach (var episode in episodes)

{

   Console.WriteLine(episode.ToString());

}

Not sure if it matters, but I used ReadAsStringAsync() though, not ReadAsAsync().  

Cheers,

-Sean

xiaoyan wrote re: WebApi and Json Deserialization into an object model
on 03-08-2012 1:22 AM

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.

xiaoyan wrote re: WebApi and Json Deserialization into an object model
on 03-08-2012 1:24 AM

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.

Graham wrote re: WebApi and Json Deserialization into an object model
on 04-17-2012 2:58 AM

Any idea if this can work from within Windows 8 Metro style apps? I can't seem to get it to function. ReadAsAsync<T> and ReadAsType<T> definitions cannot be found :(

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)