二进制序列化和字符串序列化
经常用json字符串序列化,倒是忘记也可做二进制序列化。
在文件上传时,如果序列化为字符串,再按字符串上传,这样是否会数据量变大呢?今天试了试
两种序列化方式:dotnet自带的BinaryFormatter和Newtonsoft
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 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要先序列化为字符串,再转到二进制,操作了两遍,同时数据大小的膨胀也较大
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步