LP on .NET

August 19, 2011

Serializing and Deserializing JSON Data

Filed under: .NET,C#,Software Development — Larry Parker @ 7:31 pm
Tags: , ,

My team is working on a web site that consumes JSON (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data.

I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.  A colleague pointed me to MSDN (always a good start) with this link, and a quick search pointed me to this site which had some nice JSON helpers.

After looking at the examples on both sites, I wrote some extension methods to make things easier.  Here’s what I came up with (after some suggestions on the method names by my team):

public static class JsonExtensionMethods
{
    /// <summary>
    /// Serializes an object to a JSON string.
    /// </summary>
    /// <typeparam name="T">The serializable class.</typeparam>
    /// <param name="entity">The object that will be serialized to JSON.</param>
    /// <returns>Returns a serialized representation of the object as a JSON string.</returns>
    public static String ToJson<T>(this T entity)
        where T : class
    {
        String result = null;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, entity);
            result = Encoding.Default.GetString(ms.ToArray());
        }

        return result;
    }

    /// <summary>
    /// Deserializes a JSON string into an object.
    /// </summary>
    /// <typeparam name="T">The class to deserialize the JSON string into.</typeparam>
    /// <param name="jsonObject">The serialized object as a JSON string.</param>
    /// <returns>Returns an instance of the concrete class representing the JSON string.</returns>
    public static T FromJson<T>(this String jsonObject)
        where T : class
    {
        T entity = Activator.CreateInstance<T>();

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonObject)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            entity = (T)serializer.ReadObject(ms);
        }

        return entity;
    }
}

Here are some unit tests that show how they are used:

[TestMethod()]
public void SerializeTest()
{
    Customer customer = new Customer { FirstName = "Joe", LastName = "Smith" };

    String actual = customer.ToJson();

    Assert.AreEqual("{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}", actual);
}

[TestMethod()]
public void DeserializeTest()
{
    String jsonObject = "{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}";

    Customer actual = jsonObject.FromJson<Customer>();

    Assert.AreEqual("Joe", actual.FirstName);
    Assert.AreEqual("Smith", actual.LastName);
}

Both of the tests use a class called Customer that looks like this:

[DataContract]
public class Customer
{
    [DataMember]
    public String LastName { get; set; }

    [DataMember]
    public String FirstName { get; set; }
}

Notice that the ToJson extension method is applied to a class, while the FromJson extension method is applied to a string.  The extension methods are a nice touch because you don’t have to go through a static helper class in your code, but instead just use the applicable extension methods directly on your variable (depending if you’re serializing to JSON or deserializing from JSON).

Hope you like it!

Advertisements

2 Comments »

  1. This may be a stupid question, but what is the “DataContractJsonSerializer” object?

    Comment by karatestudio — June 8, 2012 @ 10:33 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: