二进制序列化和字符串序列化
经常用json字符串序列化,倒是忘记也可做二进制序列化。
在文件上传时,如果序列化为字符串,再按字符串上传,这样是否会数据量变大呢?今天试了试
两种序列化方式:dotnet自带的BinaryFormatter和Newtonsoft
private void button3_Click(object sender, EventArgs e) { MyObject obj = new MyObject { IntProperty = 1, StringProperty = "Samplk中文化e" }; obj.buf = File.ReadAllBytes("e:\\图片2.png"); //图片长度426748 BinaryFormatter formatter = new BinaryFormatter(); MemoryStream msg = new MemoryStream(); formatter.Serialize(msg, obj); byte[] ppp = msg.ToArray(); //长度427000,只比原图多一点点 msg.Position = 0; MyObject deserializedObj = formatter.Deserialize(msg) as MyObject; //DataContractSerializer } private void button4_Click(object sender, EventArgs e) { MyObject obj = new MyObject { IntProperty = 1, StringProperty = "Samplk中文化e" }; obj.buf = File.ReadAllBytes("e:\\图片2.png"); //图片长度426748 byte[] binaryData; using (var memoryStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(memoryStream)) { string json = JsonConvert.SerializeObject(obj); int len = json.Length; //字符串长度569056,比原图多了1.4万,三分之一左右,膨胀厉害 binaryWriter.Write(json); binaryData = memoryStream.ToArray();//字符串长度569065 } } // 反序列化二进制数据回对象 MyObject deserializedObject; using (var memoryStream = new MemoryStream(binaryData)) { using (var binaryReader = new BinaryReader(memoryStream)) { var json = binaryReader.ReadString(); deserializedObject = JsonConvert.DeserializeObject<MyObject>(json) as MyObject; } } } private void button5_Click(object sender, EventArgs e) { byte[] buf = File.ReadAllBytes("e:\\图片2.png"); //图片长度426748 using (var memoryStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(memoryStream)) { string json = JsonConvert.SerializeObject(buf); int len = json.Length; //字符串长度569002 binaryWriter.Write(json); byte[] binaryData = memoryStream.ToArray(); //字节数组长度569005 } } BinaryFormatter formatter = new BinaryFormatter(); MemoryStream msg = new MemoryStream(); formatter.Serialize(msg, buf); byte[] ppp = msg.ToArray(); //ppp的长度426776 } } [Serializable] public class MyObject { public int IntProperty { get; set; } public string StringProperty { get; set; } public byte[] buf { get; set; } }
以上说明:
使用BinaryFormatter序列化后数据比较短,和原数据差不多。但Newtonsoft要先序列化为字符串,再转到二进制,操作了两遍,同时数据大小的膨胀也较大