json과 대상이 서로 바뀌는 간단한 종류입니다.

5726 단어 json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;///          
using System.IO;

namespace TCBaseUnionPay.Business
{
    public class JsonHelper
    {
        public JsonHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        /// <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        
        /// </summary>
        /// <typeparam name="T">    </typeparam>
        /// <param name="szJson">JSON   </param>
        /// <returns>    </returns>
        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                return (T)dcj.ReadObject(ms);
            }
        }
    }
}

좋은 웹페이지 즐겨찾기