这里有本博客涉及到的序列化Json和Binary格式数据的Demo:点击打开链接
一、序列化成二进制格式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinarySerialization
{
class Program
{
static void Main(string[] args)
{
Person p = new Person()
{
Name = "Jhon",
Age = 11
};
Person p2 = null;
using (Stream objStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
//序列化
formatter.Serialize(objStream, p);
StreamReader sr = new StreamReader(objStream);
Console.WriteLine(sr.ReadToEnd());
//反序列化
objStream.Seek(0, SeekOrigin.Begin);
p2 = formatter.Deserialize(objStream) as Person;
}
Console.WriteLine("p2.Name={0} , p2.Age={1}", p2.Name, p2.Age);
}
}
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
三、WCF-基于数据契约实体类的序列化
1、序列化为Json格式的数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "John";
p.Age = 42;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);
//显示Json格式数据
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine("Json from of Person object: ");
Console.WriteLine(sr.ReadToEnd());
//反序列化
stream1.Position = 0;
Person p2 = (Person)ser.ReadObject(stream1);
Console.WriteLine("p2.Name={0} , p2.Age={1}", p2.Name, p2.Age.ToString());
}
}
//必须加如下特性,否则不能序列化
[DataContract]
class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
}
2、序列化成xml,类似上面的例子,需要使用到的类为DataContractSerializer,这里不再赘述。