User user = new User { ID = 1, Name = "JACK", Age = 20, Nationality = "CHINA" }; FileStream writer = new FileStream(fileName, FileMode.Create); DataContractSerializer ser =new DataContractSerializer(typeof(User)); ser.WriteObject(writer, user); writer.Close();
FileStream fs = new FileStream(fileName,FileMode.Open); XmlDictionaryReader reader =XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(User)); User deserializedUser =(User)ser.ReadObject(reader, true);
using System; using System.Runtime.Serialization; using System.IO; using System.Xml; namespace WcfDataContractSerializer { class Program { static void Main(string[] args) { try { WriteObject("DataContractSerializerExample.xml"); ReadObject("DataContractSerializerExample.xml"); } catch (SerializationException serExc) { Console.WriteLine("序列化失败"); Console.WriteLine(serExc.Message); } catch (Exception exc) { Console.WriteLine( "序列化操作失败: {0} StackTrace: {1}", exc.Message, exc.StackTrace); } finally { Console.WriteLine("按 <Enter> 键退出...."); Console.ReadLine(); } } public static void WriteObject(string fileName) { Console.WriteLine("创建User对象并序列化它"); User user = new User { ID = 1, Name = "JACK", Age = 20, Nationality = "CHINA" }; FileStream writer = new FileStream(fileName, FileMode.Create); DataContractSerializer ser =new DataContractSerializer(typeof(User)); ser.WriteObject(writer, user); writer.Close(); Console.WriteLine("序列化User对象成功,请到程序Bin目录下查看DataContractSerializerExample.xml文件"); } public static void ReadObject(string fileName) { Console.WriteLine("反序列化实例对象"); FileStream fs = new FileStream(fileName,FileMode.Open); XmlDictionaryReader reader =XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(User)); User deserializedUser =(User)ser.ReadObject(reader, true); reader.Close(); fs.Close(); Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", "ID", "Name", "Age", "Nationality"); Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", deserializedUser.ID.ToString(), deserializedUser.Name.ToString(), deserializedUser.Age.ToString(), deserializedUser.Nationality.ToString()); } } [DataContract] public class User { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Nationality { get; set; } } }
打开程序Bin目录下的DataContractSerializerExample.xml,显示结果如下:
using System; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Json; using System.Text; namespace WcfDataContractJsonSerializer { class Program { static void Main(string[] args) { try { Console.WriteLine("创建User对象并序列化它"); User user = new User { ID = 1, Name = "JACK", Age = 20, Nationality = "CHINA" }; string jsonString = Serialize<User>(user); Console.WriteLine(jsonString); Console.WriteLine("反序列化实例对象"); User deserializedUser = Deserialize<User>(jsonString); Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", "ID", "Name", "Age", "Nationality"); Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", deserializedUser.ID.ToString(), deserializedUser.Name.ToString(), deserializedUser.Age.ToString(), deserializedUser.Nationality.ToString()); } catch (SerializationException serExc) { Console.WriteLine("序列化失败"); Console.WriteLine(serExc.Message); } catch (Exception exc) { Console.WriteLine( "序列化操作失败: {0} StackTrace: {1}", exc.Message, exc.StackTrace); } finally { Console.WriteLine("按 <Enter> 键退出...."); Console.ReadLine(); } } public static string Serialize<T>(T item) { if (item == null) return string.Empty; var serializer = new DataContractJsonSerializer(item.GetType()); using (var ms = new MemoryStream()) { serializer.WriteObject(ms, item); var sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } public static T Deserialize<T>(string jsonString) { if (string.IsNullOrEmpty(jsonString)) return default(T); var ser = new DataContractJsonSerializer(typeof(T)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { T jsonObject = (T)ser.ReadObject(ms); return jsonObject; } } } [DataContract] public class User { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Nationality { get; set; } } }
using System; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Json; using System.Xml; namespace WcfSerializerCompare { class Program { static void Main(string[] args) { MemoryStream stream1 = new MemoryStream(); MemoryStream stream2 = new MemoryStream(); MemoryStream stream3 = new MemoryStream(); User user = new User { ID = 1, Name = "JACK", Age = 20, Nationality = "CHINA" }; DataContractSerializer xmlSerializer = new DataContractSerializer(typeof(User)); xmlSerializer.WriteObject(stream1, user); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(User)); jsonSerializer.WriteObject(stream2, user); DataContractSerializer binarySerializer = new DataContractSerializer(typeof(User)); XmlDictionaryWriter write = XmlDictionaryWriter.CreateBinaryWriter(stream3); binarySerializer.WriteObject(write, user); write.Flush(); Console.WriteLine("XML文本字节数大小为:{0}bytes", stream1.Length); Console.WriteLine("JSON文本字节数大小为:{0}bytes", stream2.Length); Console.WriteLine("二进制字节数大小为:{0}bytes", stream3.Length); Console.Read(); } } [DataContract] public class User { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Nationality { get; set; } } }
从上面的示例可以看出,采用Json文本传输的格式为最小,只有53个字节数。