JavaScriptSerializer – Dictionary to JSON Serialization and Deserialization

Few weeks ago I was working with the JavaScriptSerializer for serializing objects into JSON format, sending the JSON format as a parameter to a web service method and deserializing in the web service. The JavaScriptSerializer can be useful for different serialization and deserialization tasks.

In this blog post, I will show on the simplest way how you can use this JavaScriptSerializer to serialize Dictionary collection to JSON string and deserialize it back to Dictionary.

JavaScriptSerializer is a class from the System.Web.Script.Serialization namespace. So, don’t forget to include the using System.Web.Script.Serialization; (in C#.NET) or Imports System.Web.Script.Serialization (in VB.NET).

 

SERIALIZATION

For serialization purpose the JavaScriptSerializer has the following method:

- Serialize – this method serializes an object and converts it to a JSON string. This means, when we need to serialize a Dictionary, we will need to convert it to object type. This method contains +1 overloaded method. The first one accepts an object as parameter and returns string, while the second overloaded method accepts an object as first parameter and StringBuilder as second parameter where it will write the output – this method is of void type.

Serialization Dictionary to JSON

Lets first create one Dictionary collection that will contain different types of key/value pairs. The dictionary in my testing scenario will have key = string, value = object.

Creating dictionary instance:

Dictionary<string, object> dict = new Dictionary<string, object>();

Now lets add two items in the dictionary

dict.Add("id", 1);
dict.Add("title", "The title");

Up to now, the dictionary has the following two items


Next, I will create two object arrays

//objNumbers object - contains few integer values
object[] objNumbers = new object[4];
objNumbers.SetValue(5, 0);
objNumbers.SetValue(10, 1);
objNumbers.SetValue(15, 2);
objNumbers.SetValue(20, 3);

//objNS object - name+surname
object[] objNS = new object[2];
objNS.SetValue("hajan", 0);
objNS.SetValue("selmani", 1);

and add both object arrays (objNumbers & objNS) as items in the Dictionary

dict.Add("objParas", objNumbers);
dict.Add("objNameSurname", objNS);

Lets take a look in the items inside the Dictionary


 

and, at last I will add object array inside another object array – in order to make it more complex and see the real strength of this Serialize (and later Deserialize) method even when using complex objects, object arrays and even matrixes.

//colorsAndFruits object - contains another object
object[] colorsAndFruits = new object[2];

//colors
object[] objColors = new object[4];
objColors.SetValue("orange", 0);
objColors.SetValue("red", 1);
objColors.SetValue("yellow", 2);
objColors.SetValue("blue", 3);

//fruits
object[] objFruits = new object[2];
objFruits.SetValue("Apple", 0);
objFruits.SetValue("Bananna", 1);

colorsAndFruits.SetValue(objColors, 0);
colorsAndFruits.SetValue(objFruits, 1);

I have created colorsAndFruits object array. Then, two new object arrays objColors and objFruits. Have added items to both of these object arrays and at the end both object arrays are added as items in the colorsAndFruits objct array. At the end, the colorsAndFruits object array is added as item in teh Dictionary dic.Add("colorsAndFruits",colorsAndFruits). By observing what we have in debugging mode, here is how it looks like:


 

Ok, we have passed the boring part. Now lets see the interesting part – the Serialization.

As I’ve mentioned previously, by using Serialize() method we have two options. To use the first Serialize method that returns string or to use the second Serialize method that accepts two parameters where the second parameter is the StringBuilder where the JSON output string will be assigned. I will show both ways at once.

JavaScriptSerializer serializer = new JavaScriptSerializer(); //creating serializer instance of JavaScriptSerializer class

//first way
string json = serializer.Serialize((object)dict);

//second way
System.Text.StringBuilder builder = new System.Text.StringBuilder();
serializer.Serialize((object)dict, builder);

In either way, the result will be:

{"id":1,"title":"The title","objParas":[5,10,15,20],"objNameSurname":["hajan","selmani"],"ColorsAndFruits":[["orange","red","yellow","blue"],["Apple","Bananna"]]}

except that the JSON doesn’t make colorization :) – I did that in order to have clearer view of the each item we have previously assigned in the Dictionary, now you see it as valid JSON string. You can also see that the objects are displayed as JSON objects too, which is very important in order to keep the same structure when making deserialization.

 

DESERIALIZATION

With the JavaScriptSerializer, we can easily make deserialization from JSON string to any object type. Firstly, lets take a look at the three different methods for deserialization.

- Deserialize – this method is of object type and accepts two parameters – the first parameter is the JSON string while the second parameter is the Type of the object in which the JSON string will be deserialized. (supported only in 4.0 .NET Framework)

- Deserialize<T> – this method converts the JSON string to an object of type T. See the example bellow. (supported in: 3.5,4.0 .NET Framework)

- DeserializeObject – converts the JSON string to an object graph. (supported in: 3.5/4.0 .NET Framework)

Examples:

JavaScriptSerializer deserializer = new JavaScriptSerializer();

Dictionary<string,object> deserializedDictionary1 = (Dictionary<string,object>)deserializer.Deserialize(json, typeof(object));
Dictionary<string, object> deserializedDictionary2 = deserializer.Deserialize<Dictionary<string, object>>(json);
object objDeserialized = deserializer.DeserializeObject(json);

Note:  You can use the same JavaScriptSerializer serialize instance for deserialization too. There is no difference indeed. I’m just creating an deserializer instance of the class JavaScriptSerializer to make it clear on what we are currently doing.

Line by line:

Dictionary<string,object> deserializedDictionary1 = (Dictionary<string,object>)deserializer.Deserialize(json, typeof(object));

Here is the result:

You see, as result we have got Dictionary which is equal to the Dictionary we have created at the beginning of this blog post.

next line

Dictionary<string, object> deserializedDictionary2 = deserializer.Deserialize<Dictionary<string, object>>(json);

Now you have illustrated implementation of the Dictionary<T> method. The result is pretty same as previously, only here it converts the objects to an ArrayList, which in some cases might be more useful to have it as an ArrayList.

next line is

object objDeserialized = deserializer.DeserializeObject(json);

The same result as in the first case, except that here we have the result in object not Dictionary<string,object>.

 

So, this is all for this blog post. I hope the examples I’ve shown are useful to you.

Please, do not hesitate to post your comments and feedback.

You can read more about JavaScriptSerialization class on the following MSDN link: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

And for those that want to learn more about JSON, take a look at the following website: http://www.json.org/

All the best,
Hajan

18 Comments

  • Hey @Jones, thanks for your valuable comment.
    If you have time, please write me what you would like to see in my next blog posts.

  • I would like to mention that you can also use json in directly in javascript with evaluate function.

    Regards,
    Jalpesh

  • @Jalpesh, thank you for your valuable comments and contribution. I appreciate your comments a lot!

    Yes, using eval() function in JavaScript we can easily parse JSON string and create an object of it. Moreover, I've been using the Jayrock JSON implementation - a C# library that provides very good way for working with JSON in ASP.NET applications.

    Thanks once again.

    All the best to you.
    Hajan

  • I dont loke java, but it may be good

  • @Mark, it's not about 'Java' but Serialization of JSON string into C# Dictionary collection object and vice versa ;).

  • next line is
    object objDeserialized = deserializer.DeserializeObject(json);
    why Write exp:
    dynamic objDeserialized = deserializer.DeserializeObject(json); ?

  • hi

    iam getting below error
    The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

  • @surya, are you returning the result from a web service? If so, then it would be better for you to return the result as List or ArrayList and serialize/deserialize it to dictionary when returned, or you can serialize it directly to JSON. If not, you will have to show me the code line where that happens...

  • Thanx, exactly what I needed

  • Thank you for a helpful article! Do you know if JavaScriptSerializer generates a serialization assembly as an XML serializer does?
    Vladimir

  • Vladimir, thanks for your comment and question.
    As far as I know, JavaScriptSerializer does not generates serialization assembly... and yes, XML Serializer does. I have tested the JavaScriptSerializer in Sandbox-based solutions and works perfectly, comparing to the XmlSerializer which has problems due to generating the serialization assembly on fly for each serialized type...

    Hope this was helpful.

  • Concise and helpful, thank you.

  • Please keep thorwnig these posts up they help tons.

  • Thanks Johannah!

    If you have any specific area you would like to read more about, do let me know either by commenting here or through my contact form.

    I am glad my posts are helpful.

    Regards,

    Hajan

  • Hi, how do we parse this JSON in javascript?

  • Is there any library which can be used for both JSON and XML serialization/deserialization of Dictionary.

  • very helpful notes thanks a lot.

  • Hi Hajan,

    Very Useful info, I need one more help from you...

    Can you print the key and values, Including the inner array values... Plz?

    Or, any idea to get all values in the dictionary separatly?

    Thanks,

    Ragunath.S

Comments have been disabled for this content.