Thursday, November 1, 2012

JSON Serialization/Deserialization in C#


You don’t need to download an additional library to serialize/deserialize your objects to/from JSON. Since .NET 3.5, .NET can do it natively.
Add a reference to your project to “System.Web.Extensions.dll”
Let’s look at this example JSON string:
1{
2    "some_number": 108.541,
3    "date_time""2011-04-13T15:34:09Z",
4    "serial_number""SN1234"
5}
You can deserialize the previous JSON into a dictionary like so:
1using System.Web.Script.Serialization;
2
3var jss = new JavaScriptSerializer();
4var dict = jss.Deserialize<Dictionary<string,string>>(jsonText);
5
6Console.WriteLine(dict["some_number"]); //outputs 108.541
So what if your JSON is a bit more complex?
1{
2    "some_number": 108.541,
3    "date_time""2011-04-13T15:34:09Z",
4    "serial_number""SN1234"
5    "more_data": {
6        "field1": 1.0
7        "field2""hello"  
8    }
9}
Deserialize like so…
1using System.Web.Script.Serialization;
2
3var jss = new JavaScriptSerializer();
4var dict = jss.Deserialize<Dictionary<string,dynamic>>(jsonText);
5
6Console.WriteLine(dict["some_number"]); //outputs 108.541
7Console.WriteLine(dict["more_data"]["field2"]); //outputs hello
The field “more_data” gets deserialized into a Dictionary<string, object>.
You can actually just just deserialize like so:
1using System.Web.Script.Serialization;
2
3var jss = new JavaScriptSerializer();
4var dict = jss.Deserialize<dynamic>(jsonText);
5
6Console.WriteLine(dict["some_number"]); //outputs 108.541
7Console.WriteLine(dict["more_data"]["field2"]); //outputs hello
And everything still works the same. The only caveat is that you lose intellisense by using the “dynamic” data type.
Serialization is just as easy:
1using System.Web.Script.Serialization;
2
3var jss = new JavaScriptSerializer();
4var dict = jss.Deserialize<dynamic>(jsonText);
5
6var json = jss.Serialize(dict);
7Console.WriteLine(json);
Outputs…
1{
2    "some_number": 108.541,
3    "date_time""2011-04-13T15:34:09Z",
4    "serial_number""SN1234"
5    "more_data": {
6        "field1": 1.0
7        "field2""hello"  
8    }
9}

No comments:

Post a Comment