首页 > 代码库 > 序列化和反序列化
序列化和反序列化
/// <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 }
序列化和反序列化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。