Sunday, February 6, 2011

Using JSON serialization outside a web context

You usually are in a web context if you are working with JSON, where JSON serialization almost always is encapsulated by the framework. You might accidentally come across scenarios where you want to serialize and deserialize JSON in a non-web context though.

Turns out this is fairly trivial since .NET 3.5. .NET 3.5 added the JavaScriptSerializer class. You can find this class in the System.Web.Script.Serialization namespace. To access this namespace you need to reference the System.Web.Extensions assembly.

From there on out, JSON serialization is very straightforward.

In this example I'm serializing and deserializing a Robot object.

   1:  public class Robot {
   2:      public string Name { get; set; }
   3:      public string Position { get; set; }
   4:      public string HomeWorld { get; set; }
   5:   
   6:      public override string ToString() {
   7:          return string.Format("{0} ({1}) from {2}.", new object[] {Name, Position, HomeWorld});
   8:   
   9:      }
  10:  }

From object to JSON string

   1:  var robot = new Robot() {
   2:      Name = "R2-D2",
   3:      Position = "Astromech droid",
   4:      HomeWorld = "Naboo"
   5:  };
   6:   
   7:  var javascriptSerializer = new JavaScriptSerializer();
   8:  var robotAsJson = javascriptSerializer.Serialize(robot);
   9:   
  10:  Console.WriteLine("Robot as JSON: " + robotAsJson);
  11:  //Robot as JSON: {"Name":"R2-D2","Position":"Astromech droid","HomeWorld":"Naboo"}

From JSON string to object

   1:  var robotFromJson = javascriptSerializer.Deserialize<Robot>(robotAsJson);
   2:   
   3:  Console.WriteLine("Robot as object: " + robotFromJson);
   4:  //Robot as object: R2-D2 (Astromech droid) from Naboo.

If you are looking for a way to use JSON serialization in a web context, you might want to read these articles:

2 comments:

  1. Hi,

    There are faster alternatives than the native library. Look here for a comparision:

    http://daniel.wertheim.se/2011/02/07/json-net-vs-servicestack/

    //Daniel

    ReplyDelete
  2. I don't see any numbers on the native implementation?

    ReplyDelete