In C#, when you have to work with JSON data you’re usu­ally rep­re­sented with two choices – Dat­a­Con­trac­tJ­son­Se­ri­al­izer or JavaScript­Se­ri­al­izer. There are other pop­u­lar third-party 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 differ.

Dat­a­Con­tracts

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

This makes per­fect sense as the pri­mary pur­pose of the Dat­a­Con­trac­tJ­son­Se­ri­al­izer is to be used with WCF, and just as its name sug­gests, it’s a JSON seri­al­izer 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­izer with anony­mous types.

On the other hand, with the JavaScript­Se­ri­al­izer at least you can eas­ily seri­al­ize an instance of an anony­mous type:

   1: var jsSerializer = new JavaScriptSerializer();

   2:  

   3: // define an anonymous type

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

   5:  

   6: // this writes:

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

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

Unfor­tu­nately 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 constructor.

Dic­tio­nar­ies

Another main func­tional dif­fer­ence between these two seri­al­iz­ers is how they deal with dictionaries.

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­izer seri­al­izes dic­tio­nar­ies as an array of Key­Val­ue­Pair objects:

[{“Key”:“Id”,“Value”:“35285943-32d0-45d9-ada6-eb570f757d85”},{“Key”:“Name”,“Value”:“Yan”},{“Key”:“Age”,“Value”:29}]

whereas the JavaScript­Se­ri­al­izer seri­al­izes dic­tio­nar­ies in a much more ‘JSON’ way:

{“Id”:“35285943-32d0-45d9-ada6-eb570f757d85”,“Name”:“Yan”,“Age”:29}

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­nated 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 responses we came across was a dic­tio­nary whose keys were numeric IDs like this:

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

In cases 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­izer!

Share