经常用json字符串序列化,倒是忘记也可做二进制序列化。
在文件上传时,如果序列化为字符串,再按字符串上传,这样是否会数据量变大呢?今天试了试
两种序列化方式:dotnet自带的BinaryFormatter和Newtonsoft
private void button3_Click(object sender, EventArgs e) { MyObject obj = new MyObject { IntProperty = 1, StringProperty = "Samplk中文化e" }; obj.buf = new byte[2000]; obj.buf[0] = 3; BinaryFormatter formatter = new BinaryFormatter(); MemoryStream msg = new MemoryStream(); formatter.Serialize(msg, obj); byte[] ppp = msg.ToArray(); //长度2252 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 = new byte[2000]; obj.buf[0] = 3; byte[] binaryData; using (var memoryStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(memoryStream)) { var json = JsonConvert.SerializeObject(obj); //json长度2742 binaryWriter.Write(json); binaryData = memoryStream.ToArray(); //长度2732 } } // 反序列化二进制数据回对象 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要先序列化为字符串,再转到二进制,操作了两遍,同时数据大小的膨胀也较大
标签:MyObject,obj,二进制,json,字符串,new,byte,序列化 From: https://www.cnblogs.com/81/p/18334934