JSON (JavaScript Object Notation) provides a convenient way to serialize an object, like "Employee" with first and last name, to a string. This can be very useful in Silverlight apps, such as when you need to pass complex objects to and from a web service.
There are APIs in Silverlight that make it relatively easy to roundtrip an object from a JSON string and back. Here are two wrapper methods.
These use the assemblies System.IO and System.ServiceModel.Web (which contains the necessary namespace System.Runtime.Serialization.Json). It also uses the two static utility methods I blogged about to roundtrip from a MemoryStream and back (GetMemoryStreamFromString and GetStringFromMemoryStream).
public static T ConvertFromJSON
{
System.Runtime.Serialization.Json.DataContractJsonSerializer d =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
MemoryStream m = GetMemoryStreamFromString(strJSON);
T obj = (T)d.ReadObject(m);
return obj;
}
public static string ConvertToJSON
{
System.Runtime.Serialization.Json.DataContractJsonSerializer d =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
MemoryStream m = new MemoryStream();
d.WriteObject(m, obj);
string strJSON = GetStringFromMemoryStream(m);
return strJSON;
}
I assume that the code is self-explanatory. Perhaps the only note is that it uses Generics to dynamically set the return type. You could also optimize the methods for performance by instantiating the DataContractJsonSerializer once, and making these utility methods, as opposed to static methods that re-create it every time.