赞
踩
上一张内容,序列化之JAVA原生序列化
直接上代码了
public class HessianSerializerUtil {
public static <T> byte[] serialize(T obj) {
byte[] bytes = null;
// 1、创建字节输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 2、对字节数组流进行再次封装
// step 1. 定义外部序列化工厂
//ExtSerializerFactory extSerializerFactory = new ExtSerializerFactory();
//extSerializerFactory.addSerializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisSerializer());
//extSerializerFactory.addDeserializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisDeserializer());
// step 2. 序列化工厂
//SerializerFactory serializerFactory = new SerializerFactory();
//serializerFactory.addFactory(extSerializerFactory);
HessianOutput hessianOutput = new HessianOutput(bos);
//hessianOutput.setSerializerFactory(serializerFactory);
try {
// 注意,obj 必须实现Serializable接口
hessianOutput.writeObject(obj);
bytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
public static <T> T deserialize(byte[] data) {
if (data == null) {
return null;
}
// 1、将字节数组转换成字节输入流
ByteArrayInputStream bis = new ByteArrayInputStream(data);
// step 1. 定义外部序列化工厂
//ExtSerializerFactory extSerializerFactory = new ExtSerializerFactory();
//extSerializerFactory.addSerializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisSerializer());
//extSerializerFactory.addDeserializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisDeserializer());
// step 2. 序列化工厂
//SerializerFactory serializerFactory = new SerializerFactory();
//serializerFactory.addFactory(extSerializerFactory);
HessianInput hessianInput = new HessianInput(bis);
//hessianInput.setSerializerFactory(serializerFactory);
Object object = null;
try {
object = hessianInput.readObject();
} catch (IOException e) {
e.printStackTrace();
}
return (T) object;
}
}
pom依赖
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
不过这个序列化不支持OffsetDateTime类型属性
下一章来讲protostuff序列化
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。