序列化-Hessian
引用官网介绍:
Hessian is a dynamically-typed, binary serialization and Web Services protocol designed for object-oriented transmission.
Hessian 是动态类型、二进制、紧凑的,并且可跨语言移植的一种序列化框架。Hessian 协议要比 JDK、JSON 更加紧凑,性能上要比 JDK、JSON 序列化高效很多,而且生成的字节数也更小。
代码示例如下:
1 @Data 2 public class SimplePOJO implements Serializable { 3 String field1; 4 String field2; 5 public SimplePOJO(String s1, String s2) { 6 field1 = s1; 7 field2 = s2; 8 } 9 // fastjson逆序列化时要求对象必须要有一个默认的构造函数 10 public SimplePOJO(){} 11 } 12 public static void main(String[] args) throws IOException, ClassNotFoundException { 13 SimplePOJO student = new SimplePOJO("16","张三"); 14 //把student对象转化为byte数组 15 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 16 Hessian2Output output = new Hessian2Output(bos); 17 output.writeObject(student); 18 output.flushBuffer(); 19 byte[] data = bos.toByteArray(); 20 bos.close(); 21 22 // 把字节流存入文件 23 FileOutputStream fos = new FileOutputStream("C:\\Users\\user\\Desktop\\student.dat"); 24 fos.write(data); 25 fos.close(); 26 // 从文件中读取字节流 27 FileInputStream fis = new FileInputStream( "C:\\Users\\user\\Desktop\\student.dat"); 28 byte[] bytes = new byte[fis.available()]; 29 fis.read(bytes); 30 31 // 转化为student对象 32 ByteArrayInputStream bis = new ByteArrayInputStream(data); 33 Hessian2Input input = new Hessian2Input(bis); 34 SimplePOJO deStudent = (SimplePOJO) input.readObject(); 35 input.close(); 36 System.out.println(deStudent); 37 }
打开保存的中间文件看看:
可以看到有类名以及属性名和对应值
具体的数据-byte类型的映射可以参考官网http://hessian.caucho.com/doc/hessian-serialization.html
对于上述代码,其数据类型为Object类型。Object类型转换格式为(官网):
1 class Car { 2 String color; 3 String model; 4 } 5 6 out.writeObject(new Car("red", "corvette")); 7 out.writeObject(new Car("green", "civic")); 8 9 --- 10 11 C # object definition (#0) 12 x0b example.Car # type is example.Car 13 x92 # two fields 14 x05 color # color field name 15 x05 model # model field name 16 17 O # object def (long form) 18 x90 # object definition #0 19 x03 red # color field value 20 x08 corvette # model field value 21 22 x60 # object def #0 (short form) 23 x05 green # color field value 24 x05 civic # model field value