C# Code, Tutorials and Full Visual Studio Projects

Serialize to JSON

Posted by on Nov 16, 2010 in Code Snippets | 0 comments

Serialize to JSON

While it doesn’t seem very well known, .NET does have a nice library to serialize objects to JSON. What is even nicer is it lets you serialize dictionaries without a fuss! (take that XmlSerializer!)

The following c# code shows how to make extension methods you can include in your project that will let you convert any object you like into JSON or from JSON.




You will need to add a reference to System.Runtime.Serialization


C# JSON Extension Methods

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Jarloo
{
    public static class Extensions
    {
        public static string ToJson<T>(this T obj)
        {
            MemoryStream stream = new MemoryStream();

            try
            {
                DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
                jsSerializer.WriteObject(stream, obj);

                return Encoding.UTF8.GetString(stream.ToArray());
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }

        public static T FromJson<T>(this string input)
        {
            MemoryStream stream = new MemoryStream();

            try
            {
                DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
                stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
                T obj = (T) jsSerializer.ReadObject(stream);

                return obj;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }
    }
}



You can call the the c# extension methods for JSON like so:

using System;
using System.Collections.Generic;

namespace Jarloo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Dictionary<int, string> myObjects = new Dictionary<int, string>();

            myObjects.Add(1, "This");
            myObjects.Add(2, "is");
            myObjects.Add(3, "cool");

            string json = myObjects.ToJson();
            Console.WriteLine(json);

            Dictionary<int, string> myObjects2 = json.FromJson<Dictionary<int, string>>();
        }
    }
}



Compared to XML, I find JSON so much better. The payload is much smaller, especially when dealing with large files, and if your working with Javascript through your ASP.NET having something like this makes the process go so much easier.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>