Home > .net 3.5, c#, JavaScript, Microsoft, Visual Studio 2008 > Update Obsolete JavaScriptSerializers

Update Obsolete JavaScriptSerializers

April 2, 2008

I have three extension methods in a shared library we use that convert Json back and forth.  The “obsolete” JavaScriptSerializers work just fine—as long as I ignore the warnings from Visual Studio whenever I modify the library.

Along with a few other changes, I set off today to update those extension methods to the new DataContractJsonSerializer.  What a pain.

Here’s what it takes—step-by-step.

1. Decorate all of the classes you wish to serialize with the [Serializable].  This is easy enough for internal, controlled classes.  The [DataContract] attributes do not appear to be needed (feedback?).

[Serializable]

public sealed class School { }

2. Change your two to three lines of simple code into painful MemoryStreams.

The old code, which can be found here, was pretty darned simple.  Use the JavaScriptSerializer and either Serialize or Deserialize.  One returned a string, one returned the object.

Unfortunately, the new DataContractJsonSerializer is a bit more complicated on both sides.

The ToJson extension method:

public static string ToJson(this object obj)

{

var serializer =

new DataContractJsonSerializer(obj.GetType());

      

using (var stream = new MemoryStream())

       {

             serializer.WriteObject(stream, obj);

             return Encoding.Unicode.GetString(stream.ToArray());

}

}

The FromJson extension method:

public static T FromJson<T>(this object obj)

{

var returnObject =

Activator.CreateInstance<T>();

       var serializer =

new DataContractJsonSerializer(returnObject.GetType());

 

using (var stream = new

MemoryStream(Encoding.Unicode.GetBytes(obj.ToString())))

{

              return (T) serializer.ReadObject(stream);

}

}

Gone are the Serialize and Deserialize methods; replaced by ReadObject and WriteObject.  Unfortunately to read/write, a stream is required.  It’s not ‘terrible,’ but is another object to create and destroy.

3. Rerun unit tests.

Thank goodness for tests—nuff said. :)

That’s it.  So far, both the tests and the few places I’d ran additional, manual tests of data objects<->Json, things have worked well with these new methods.  I’d love to hear/understand WHY the methods changed and what benefits dumping to/from streams provides us for extensibility.  I’m sure there’s a reason.

Oh, and Visual Studio doesn’t throw warnings anymore—yay.

%d bloggers like this: