• 序列化和反序列化


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

      

  • 相关阅读:
    第 16 章 CSS 盒模型[下]
    第 16 章 CSS 盒模型[上]
    第 15 章 CSS 文本样式[下]
    第 15 章 CSS 文本样式[上]
    第 14 章 CSS 颜色与度量单位
    第 13 章 CSS 选择器[上]
    第 12 章 CSS 入门
    关于springboot上传文件报错:The temporary upload location ***is not valid
    Java Enum枚举 遍历判断 四种方式(包括 Lambda 表达式过滤)
    git命令-切换分支
  • 原文地址:https://www.cnblogs.com/xiaoyu369/p/4112334.html
Copyright © 2020-2023  润新知