asp.net序列化与反序列化

  反序列化例子:  Qresponse = (QualityResponse)Deserialize(typeof(QualityResponse), xml);


序列化是将对象状态转换为可保持或传输的格式的过程,比如转化为二进制、xml、json等的过程。

与序列化相对的是反序列化,它将流转换为对象,也就是将在序列化过程中所生成的二进制串、xml、json等转换成数据结构或者对象的过程


对象与XML转化


 ///  
        /// 反序列化  
        ///
 
        /// 类型  
        /// XML字符串  

        ///  


        public object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {

                return e.Message;
            }

        }



        ///  
        /// 序列化  
        ///
 
        /// 类型  
        /// XML字符串  
        ///  
        public string Serialize(object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            StringBuilder sbXml = new StringBuilder();
            using (StringWriter writer = new StringWriter(sbXml))
            {
                serializer.Serialize(writer, obj);
            }
            return sbXml.ToString();
        }

你可能感兴趣的:(asp.net序列化与反序列化)