JSON Helper

7951 단어 json
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ServiceModel.Web;///          

using System.Runtime.Serialization.Json;

using System.IO;

using System.Text;



namespace Sigil.Common

{

    /// <summary>

    /// JSON   

    /// </summary>

    public class JsonHelper

    {

        /// <summary>

        ///        JSON     

        /// </summary>

        /// <typeparam name="T">    </typeparam>

        /// <param name="obj">    </param>

        /// <returns>JSON   </returns>

        public static string GetJson<T>(T obj)

        {

            //        System.ServiceModel.Web 

            /**

             *           ,System.Runtime.Serialization.Json; Json      

             * */

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));

            using (MemoryStream ms = new MemoryStream())

            {

                json.WriteObject(ms, obj);

                string szJson = Encoding.UTF8.GetString(ms.ToArray());

                return szJson;

            }

        }



        /// <summary>

        /// Json    ,       Json        

        /// </summary>

        /// <typeparam name="T">    </typeparam>

        /// <param name="jsonString">JSON   </param>

        /// <returns>    </returns>

        public static T ParseFormJson<T>(string jsonString)

        {

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))

            {

                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);

            }

        }



        /// <summary>

        /// JSON   

        /// </summary>

        public static string JsonSerializer<T>(T t)

        {

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            MemoryStream ms = new MemoryStream();

            ser.WriteObject(ms, t);

            string jsonString = Encoding.UTF8.GetString(ms.ToArray());

            ms.Close();

            return jsonString;

        }



        /// <summary>

        /// JSON    

        /// </summary>

        public static T JsonDeserialize<T>(string jsonString)

        {

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

            T obj = (T)ser.ReadObject(ms);

            return obj;

        }

    }

}

참조:
   http://www.cnblogs.com/zhaozhan/archive/2011/01/09/1931340.html
       http://www.cnblogs.com/yylp521/p/3148856.html

좋은 웹페이지 즐겨찾기