C#序列化及反序列化Json对象通用类JsonHelper

当今的程序界Json大行其道。因为Json对象具有简短高效等优势,广受广大C#码农喜爱。这里发一个序列化及反序列化Json对象通用类库,希望对大家有用。

    public class JsonHelper
    {
        #region 对象类型序列化为json 字符
        /// <summary>
        /// 对象类型序列化为json 字符
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="jsonObject">待转换实体</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>string</returns>
        public static string ObjectToJson<T>(Object jsonObject, Encoding encoding)
        {
            string result = String.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, jsonObject);
                result = encoding.GetString(ms.ToArray());
            }
            return result;
        }
        #endregion

        #region json字符反序列化为对象
        /// <summary>
        /// json字符反序列化为对象
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>T</returns>
        public static T JsonToObject<T>(string json, Encoding encoding)
        {
            T resultObject = default(T);
            try
            {
                resultObject = Activator.CreateInstance<T>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(encoding.GetBytes(json)))
                {
                    resultObject = (T)serializer.ReadObject(ms);
                }
            }
            catch { }
            return resultObject;
        }
        #endregion
    }

 

posted @ 2016-09-06 11:06  clown  阅读(5019)  评论(0编辑  收藏  举报