zoukankan      html  css  js  c++  java
  • 序列化和反序列化

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

      

  • 相关阅读:
    ROS编程中使用rosed编写代码
    ROS中.launch文件的remap标签详解
    Ubuntu下网易云音乐无法联网的解决办法
    双舵轮AGV里程计、运动控制核心算法
    PID参数调整的口诀
    altium designer生成gerber步骤
    SLAM FOR DUMMIES 第5-8章 中文翻译
    SLAM for Dummies SLAM初学者教程 中文翻译 1到4章
    有关ros::spin()和ros::spinonce()若干感受
    ROS,launch学习
  • 原文地址:https://www.cnblogs.com/xiaoyu369/p/4112334.html
Copyright © 2011-2022 走看看