博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

序列化和反序列化

Posted on 2014-11-21 11:01  生命如风  阅读(135)  评论(0编辑  收藏  举报
    /// <summary>
    /// 序列化帮助类
    /// </summary>
    public class SerializeHelp
    {
        #region XML序列化
        /// <summary>
        /// XML序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string XMLSerialize<T>(T t)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());
                xz.Serialize(sw, t);
                return sw.ToString();
            }
        }

        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        public static T XMLDeserialize<T>(T t, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());

                return (T)xz.Deserialize(sr);
            }
        }
        #endregion

        #region JSON序列化和反序列化
        /// <summary>
        /// JSON序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JSONSerialize(object jsonObject)
        {

            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
           
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        public static T JSONDeserialize<T>(string jsonString)
        {
            using (var memory = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
            {
                var serialize = new DataContractJsonSerializer(typeof(T));
                return (T)serialize.ReadObject(memory);
            }
        }
        #endregion

    }