首页 > 代码库 > 序列化和反序列化

序列化和反序列化

    /// <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    }

  

序列化和反序列化