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