C# 二进制、Xml、Json序列化和反序列化
昨天利用业余时间对比了下C#中三种序列化方式(二进制、Xml、Json),综合来看json方式生成的字节数组长度最短,但当你需要序列化的对象中包括byte[]类型,且其长度较长时,序列化后,xml方式的长度较json方式更短。xml方式中对byte[]做了base64转换。
最后综合三种情况,写了一个基于泛型的通用类来完成序列化和反序列化操作,仅供参考,若有什么错误之处,还请指教。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Json; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Leaf.Lib.Data { /// <summary> /// 对象序列化/反序列化 /// </summary> public class Serialization { /// <summary> /// 序列化类型 /// </summary> public enum SerializeType { Binary, Json, Xml } /// <summary> /// 对象反序列化 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="aSerializeData">序列化字节数组</param> /// <param name="aType">序列化方式</param> /// <returns></returns> public static T Deserialize<T>(byte[] aSerializeData, SerializeType aType) { T obj = default(T); ; if (aSerializeData != null && aSerializeData.Length > 0) { MemoryStream stream = new MemoryStream(aSerializeData); switch (aType) { case SerializeType.Binary: BinaryFormatter bf = new BinaryFormatter(); obj = (T)bf.Deserialize(stream); break; case SerializeType.Json: DataContractJsonSerializer djs = new DataContractJsonSerializer(typeof(T)); obj = (T)djs.ReadObject(stream); break; case SerializeType.Xml: XmlSerializer xs = new XmlSerializer(typeof(T)); obj = (T)xs.Deserialize(stream); break; } stream.Close(); } return obj; } /// <summary> /// 对象序列化 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="aData">需要序列化的对象</param> /// <param name="aType">序列化方式</param> /// <returns></returns> public static byte[] Serialize<T>(T aData, SerializeType aType) { MemoryStream stream = new MemoryStream(); switch (aType) { case SerializeType.Binary: BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, aData); break; case SerializeType.Json: DataContractJsonSerializer djs = new DataContractJsonSerializer(typeof(T)); djs.WriteObject(stream, aData); break; case SerializeType.Xml: XmlSerializer xs = new XmlSerializer(typeof(T)); xs.Serialize(stream, aData); break; } byte[] data = stream.ToArray(); stream.Close(); return data; } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。