Using Json.NET to Serialize objects

June 24, 2012 — 2 Comments

Json.NET is a popular high-performance JSON framework for .NET

Features

  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance, faster than .NET’s built-in JSON serializers
  • Write indented, easy to read JSON
  • Convert JSON to and from XML
  • Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8 Metro

Serialization Wrapper

The following is a wrapper I wrote to wrap boiler plate code and facilitate reuse.

public sealed class SerializerWrapper 
{
    readonly JsonSerializer serializer = new JsonSerializer();

    public void Serialize(Stream ms, object obj)
    {
        var jsonTextWriter = new JsonTextWriter(new StreamWriter(ms));
        serializer.Serialize(jsonTextWriter,obj);
        jsonTextWriter.Flush();
        ms.Position = 0;
    }

    public TType Deserialize<TType>(Stream ms)
    {
        var jsonTextReader = new JsonTextReader(new StreamReader(ms));
        return serializer.Deserialize<TType>(jsonTextReader);
    }
}

Using the SerializationWrapper

[TestClass]
public class SerializationWrapperUnitTest {
    public class TestObject {
        public string Message { get; set; }
        public string By { get; set; }
    }

    [TestMethod]
    public void SerializeObject()
    {
        var obj = new TestObject {
            By = "Alexandre Brisebois",
            Message = "This is a test Message" };

        var s = new SerializationWrapper();

        string serializedObject;

        using(var ms = new MemoryStream())
        {
            s.Serialize(ms, obj);

            TextReader reader = new StreamReader(ms);

            serializedObject = reader.ReadToEnd();
        }

        Debug.WriteLine(serializedObject);
        Assert.IsFalse(string.IsNullOrWhiteSpace(serializedObject));
    }
}

Resulting JSON Object

{"Message":"This is a test Message","By":"Alexandre Brisebois"}

2 responses to Using Json.NET to Serialize objects

  1. 

    How do you deal with special characters? Is there a library to reference when deserializing? Suppose in your example there are an extra pair of double-quotes like so, {“Message”:”This is a “test” Message”,”By”:”Alexandre Brisebois”}, could you deserialize it without writing a method to add back-slashes to it.
    I really do like your example though, especially the way you include your testing method!
    Thank you very much.

    Like

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