.NET对象序列化的几种方式

设有对象:

 

代码
public class Person
    {
        
public string Name
        {           
            
getset;       
        }
        
public int Age
        {
            
getset;
        }
        
public string Address
        {
            
getset;
        }
    }
  Person p 
= new Person{Name = "McJeremy",Age = 25, Address = "ShenZhen"};

 

现在使用以下几种方式对其序列化: 

1、使用 BinaryFormatter

 

代码
FileStream fs = new FileStream(@"D:/person.txt", FileMode.OpenOrCreate, FileAccess.Write);
            BinaryFormatter bf 
= new BinaryFormatter();
            
try
            {
                bf.Serialize(fs, p);
//反序列化 object obj=bf.Deserialize(fs)
                fs.Close();
            }
            
catch
            {
            }

 

2、使用XmlSerializer

 

代码
FileStream fs = new FileStream(@"D:/person.xml", FileMode.OpenOrCreate, FileAccess.Write);
            XmlSerializer xs 
= new XmlSerializer(typeof(Person));
            
try
            {
                xs.Serialize(fs, p);
                
//反序列化 object obj=xs.Deserialize(fs)
                fs.Close();
            }
            
catch
            {
            }

 

序列化结果:

 

代码
<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  
<Name>Xu</Name>
  
<Age>25</Age>
  
<Address>ShenZhen</Address>
</Person>

 

/***使用DataContract及DataContractJson时,需要在Person类及其属性上添加DataContract&&DataMember属性,如下:

 

代码
[DataContract]
    
public class Person
    {
        [DataMember(Order
=1)]
        
public string Name
        {
            
get;
            
set;
        }
        [DataMember(Order 
= 2)]
        
public int Age
        {
            
get;
            
set;
        }
        [DataMember(Order 
= 3)]
        
public string Address
        {
            
get;
            
set;
        }
    } 

 

 

3、使用DataContractSerializer(结果存为xml格式 )

 

代码
 using (FileStream fs = new FileStream(@"D:/person_DataContract.xml", FileMode.OpenOrCreate, FileAccess.Write))
            {
                DataContractSerializer ds 
= new DataContractSerializer(typeof(Person));
                ds.WriteObject(fs, p);
            }

//结果:
 <Person xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Name>Xu</Name><Age>25</Age><Address>ShenZhen</Address></Person>

 

 

4、在System.ServiceModel.web.dll中,还有个DataContractJsonSerializer,结果存为Json格式

代码
 using (FileStream fs = new FileStream(@"D:/person_DataContractJson.txt", FileMode.OpenOrCreate, FileAccess.Write))
            {
                DataContractJsonSerializer ds 
= new DataContractJsonSerializer(typeof(Person));
                ds.WriteObject(fs, p);
            }
//结果:
{"Name":"McJeremy","Age":25,"Address":"ShenZhen"}

 

 

 

posted @ 2010-03-16 11:15  mcjeremy  阅读(1670)  评论(0编辑  收藏  举报
------------------------------------ 心静似高山流水不动,心清若巫峰雾气不沾 ------------------------------------