JSON serialization – DataContractJsonSerializer vs JavaScriptSerializer

In C#, when you have to work with JSON data you’re usu­al­ly rep­re­sent­ed with two choic­es – Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er or JavaScript­Se­ri­al­iz­er. There are oth­er pop­u­lar third-par­ty libraries out there, such as the pop­u­lar Json.Net project, but for the rest of this blog let’s just focus on the two built-in JSON seri­al­iz­ers and see how they dif­fer.


With­out doubt the biggest dif­fer­ence between the two is that Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er only works with types dec­o­rat­ed with the Dat­a­Con­tract attribute, but JavaScript­Se­ri­al­iz­er can work with any object.

This makes per­fect sense as the pri­ma­ry pur­pose of the Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er is to be used with WCF, and just as its name sug­gests, it’s a JSON seri­al­iz­er for Dat­a­Con­tract types.

Anony­mous Types

One inter­est­ing side effect of the above is that you can’t use Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er with anony­mous types.

On the oth­er hand, with the JavaScript­Se­ri­al­iz­er at least you can eas­i­ly seri­al­ize an instance of an anony­mous type:

   1: var jsSerializer = new JavaScriptSerializer();


   3: // define an anonymous type

   4: var anonymous = new { Id = Guid.NewGuid(), Name = "Yan", Age = 29 };


   6: // this writes:

   7: // {"Id":"2edebefb-2585-438c-bbc3-939e7688f630","Name":"Yan","Age":29}

   8: Console.WriteLine(jsSerializer.Serialize(anonymous));

Unfor­tu­nate­ly you won’t be able to dese­ri­al­ize the JSON string back into an anony­mous type as all the avail­able dese­ri­al­ize meth­ods requires a type which has a para­me­ter­less con­struc­tor.


Anoth­er main func­tion­al dif­fer­ence between these two seri­al­iz­ers is how they deal with dic­tio­nar­ies.

Take this sim­ple dic­tio­nary for instance:

   1: var dictionary = new Dictionary<string, object>();

   2: dictionary.Add("Id", Guid.NewGuid());

   3: dictionary.Add("Name", "Yan");

   4: dictionary.Add("Age", 29);

The Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er seri­al­izes dic­tio­nar­ies as an array of Key­Val­ue­Pair objects:


where­as the JavaScript­Se­ri­al­iz­er seri­al­izes dic­tio­nar­ies in a much more ‘JSON’ way:


This sub­tle dif­fer­ent might seem triv­ial at first, but it can make a huge dif­fer­ence when you’re deal­ing with data that are orig­i­nat­ed from a non-.Net lan­guage. A per­fect exam­ple came cou­ple of days ago when we were test­ing out the Face­book graph API and one of the JSON respons­es we came across was a dic­tio­nary whose keys were numer­ic IDs like this:

{“1652438520054”:{“id”:“1652438520054”, …}}

In cas­es like this, you sim­ply won’t be able to dese­ri­al­ize this JSON using the Dat­a­Con­trac­tJ­son­Se­ri­al­iz­er!