Serializes/Deserializes source into a JSON string. : Json « Network « C# / C Sharp






Serializes/Deserializes source into a JSON string.

 


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

internal static class JSON
{
    public static string Stringify<T>(T source) where T : class
    {
        string ret = null;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream memoryStream = new MemoryStream())
        {
            serializer.WriteObject(memoryStream, source);
            memoryStream.Flush();
            memoryStream.Position = 0;
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                ret = reader.ReadToEnd();
            }
        }
        return ret;
    }
    public static T Parse<T>(string source) where T : class
    {
        T ret = null;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                writer.Write(source);
                writer.Flush();
                memoryStream.Position = 0;
                ret = serializer.ReadObject(memoryStream) as T;
            }
        }
        return ret;
    }
}

   
  








Related examples in the same category

1.JSON (JavaScript Object Notation) Utility Methods.
2.DataContractJsonSerializer Demo
3.Creates a JSON graph of all of the field's client-side data
4.Removes Json null objects from the serialized string and return a new string(Extention Method)
5.Json String To Byte Array