Serialize Object Using Json


If you want to serialize any object to or from JSON (JavaScript object Notation). You can use DataContract JsonSerializer's WriteObject and ReadObject methods to serialize and deserialize respectively. Following is the small example code:

Note: you must include the reference to System.Runtime.Serialization assembly

using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.Linq;
using System.IO;
using System.Text;

namespace
SerializeObjectUsingJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a list of string
            List<string> list = new List<string>()
            {
                "item1","item2","item3","item4","item5"
            };
            //create memorystream
            MemoryStream memoryStream = new MemoryStream();
            //create Json serializer
            //constructor argument must contain the type of object that is to be serailized/deserialized
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(list.GetType());
            //serialize the list
            serializer.WriteObject(memoryStream, list);
            //get Json string from stream
            string str = Encoding.Default.GetString(memoryStream.ToArray());
            //write the string to console
            Console.WriteLine(str);
            //read Json data to stream
            memoryStream = new MemoryStream(Encoding.Default.GetBytes(str));
            //deserialize list
            list = serializer.ReadObject(memoryStream) as List<string>;
            //strings in the list
            foreach (string s in list)
                Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}

Output:

JSON.gif

To serialize any datatype use [Serializable] annotation

[Serializable]
    class JasonTypeFull
    {
        public string property1 { get; set; }
        public string property2 { get; set; }
        public string property3 { get; set; }
    }


Or you can use [DataContract] and [DataMember] to selectively serialize class members

[DataContract]
    class JasonTypePartial
    {
        [DataMember]
        public string property1 { get; set; }
        public string property2 { get; set; }
        [DataMember]
        public string property3 { get; set; }
    }


Similar Articles