Serialize and Deserialize with JSON : example

 

 

 class Program
    {
       
static void Main(string
[] args)
        {
           
var human1 = new Human
() {
                Name =
"Joe"
,
                Age = 30,
                Children =
new List<Human
>
                {
                   
new Human() {Name="Jim"
, Age=3},
                   
new Human() {Name="July"
, Age=2}
                }
                };

           
var human2 = new Human
()
            {
                Name =
"Joe1"
,
                Age = 31,
                Children =
new List<Human
>
                {
                   
new Human() {Name="Jim1"
, Age=32},
                   
new Human() {Name="July2"
, Age=22}
                }
            };

           
var listHuman = new List<Human
>();
            listHuman.Add(human1);
            listHuman.Add(human2);

           
//Serialize the object.
            var
hstr = listHuman.JsonSerialize();

           
//Create a cloned object by deserializing the same
            var cloned = hstr.JsonDeserialize<List<Human
>>();

        }
    }

   
public class Human
    {
       
public List<Human> Children { get; set
; }
       
public string Name { get; set
; }
       
public int Age { get; set
; }
    }

   
public static class JsonSerializerHelper
    {
       
/// <summary>
        /// Adds an extension method to a string
        /// </summary>
        /// <typeparam name="TObj">The expected type of Object</typeparam>
        /// <param name="json">Json string data</param>
        /// <returns>The deserialized object graph</returns>
        public static TObj JsonDeserialize<TObj>(this string
json)
        {
           
using (MemoryStream mstream = new MemoryStream(Encoding
.Unicode.GetBytes(json)))
            {
               
DataContractJsonSerializer
serializer =
                        
new DataContractJsonSerializer(typeof
(TObj));

               
return
(TObj)serializer.ReadObject(mstream);
            }
        }

       
/// <summary>
        /// Serialize the object to Json string
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>Serialized string</returns>
        public static string JsonSerialize(this object
obj)
        {
           
using (MemoryStream mstream = new MemoryStream
())
            {
               
DataContractJsonSerializer
serializer =
                       
new DataContractJsonSerializer
(obj.GetType());
                serializer.WriteObject(mstream, obj);
                mstream.Position = 0;

               
using (StreamReader reader = new StreamReader
(mstream))
                {
                   
return
reader.ReadToEnd();
                }
            }
        }
    }

Comments

Popular posts from this blog

Setup SharePoint 2010

Register CSS to SP Master Page