Quick JSON Serialization/Deserialization in C#

*This outdated*. You should use FridayThe13th the best JSON parser for Silverlight and .NET 4.0.

You don't need to download an additional libraryto 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:

{
    "some_number": 108.541, 
    "date_time": "2011-04-13T15:34:09Z", 
    "serial_number": "SN1234"
}

You can deserialize the previous JSON into a dictionary like so:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,string>>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541

So what if your JSON is a bit more complex?

{
    "some_number": 108.541, 
    "date_time": "2011-04-13T15:34:09Z", 
    "serial_number": "SN1234"
    "more_data": {
        "field1": 1.0
        "field2": "hello"   
    }
}

Deserialize like so...

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,dynamic>>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.WriteLine(dict["more_data"]["field2"]); //outputs hello

The field "more_data" gets deserialized into a Dictionary\.

You can actually just just deserialize like so:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.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:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

var json = jss.Serialize(dict);
Console.WriteLine(json);

Outputs... [sourcecode language="javascript"] { "some_number": 108.541, "date_time": "2011-04-13T15:34:09Z", "serial_number": "SN1234" ```

If you made it this far, you should follow me on Twitter.

-JP

Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus