Json、xml,二进制序列化的简单实现
本文主要是记录一下.net的几种序列化方式。
一、Json序列化
json序列化在webapi项目中是非常流行。因为json非常的直观明了,调用者能够很直观的知道返回的数据信息。
以下是基于NewtonSoft.Json简单封装的json序列化类
1 public class JsonHelper 2 { 3 ///4 /// 序列化 5 /// 6 /// 7 /// 8 /// 9 public static string Serialize (T val) 10 { 11 string result = JsonConvert.SerializeObject(val); 12 return result; 13 } 14 /// 15 /// 缩进式序列化 16 /// 17 /// 18 /// 19 /// 20 public static string SerializeIndented (T val) 21 { 22 string result = JsonConvert.SerializeObject(val, Formatting.Indented); 23 return result; 24 } 25 /// 26 /// 反序列化 27 /// 28 /// 29 /// 30 /// 31 public static T Deserial (string str) 32 { 33 var result = JsonConvert.DeserializeObject (str); 34 return result; 35 } 36 }
当然json序列化还有不少可以特性化的功能,例如指定DateTime类型的序列化格式,指定空值字段不序列化(减少数据传输的大小),指定序列化字段的名称等。
二、xml序列化
xml格式虽然比不上json简介明了,但是在蛮多情况下会使用到的。例如有些电商api就指定传输数据为xml格式。还有些配置文件有时也倾向于使用xml格式。
以下是简单的xml序列化封装
1 public class XmlHelper 2 { 3 ///4 /// 系列化 5 /// 6 /// 7 /// 8 /// 9 public static string Serialize (T val) 10 { 11 var serializer = new XmlSerializer(typeof(T)); 12 using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture)) 13 { 14 serializer.Serialize(stringWriter, val); 15 string xml = stringWriter.ToString(); 16 return xml; 17 } 18 } 19 /// 20 /// 反序列化 21 /// 22 /// 23 /// 24 /// 25 public static T Deserialize (string xmlString) 26 { 27 var serializer = new XmlSerializer(typeof(T)); 28 using (var reader = new StringReader(xmlString)) 29 { 30 var result = (T)serializer.Deserialize(reader); 31 return result; 32 } 33 } 34 35 }
三、二进制序列化
二进制序列化一般情况下数据大小会比xml,json的序列化的更小。但是二进制则不能直观的知道数据的内容信息。
二进制序列化实现
1 public class BinaryHelper 2 { 3 ///4 /// 序列化 5 /// 6 /// 7 /// 8 /// 9 public static byte[] Serialize (T val) 10 { 11 if (val == null) 12 { 13 return null; 14 } 15 var binaryFormatter = new BinaryFormatter(); 16 using (var stream = new MemoryStream()) 17 { 18 binaryFormatter.Serialize(stream, val); 19 return stream.ToArray(); 20 21 } 22 } 23 /// 24 /// 反序列化 25 /// 26 /// 27 /// 28 /// 29 public static T Deserialize (byte[] data) 30 { 31 if (data == null) 32 { 33 return default(T); 34 } 35 var binaryFormat = new BinaryFormatter(); 36 using (var stream = new MemoryStream(data)) 37 { 38 var result = (T)binaryFormat.Deserialize(stream); 39 return result; 40 } 41 } 42 }
原文:https://www.cnblogs.com/johnyong/p/14957053.html