在Java中可以实现序列化将Java对象转为二进制序列,这方便进行对象数据的传输与存储。在实际使用的过程中,将二进制序列转为String是一种常见的形式。
下面我们先介绍一种错误的互转方式,这也是我搜索时见过最多的。
public class SerializeUtils {
public static byte[] serialize(Object obj){
byte[] bytes = null;
try {
ByteArrayOutputStream baos=new ByteArrayOutputStream();;
ObjectOutputStream oos=new ObjectOutputStream(baos);
oos.writeObject(obj);
bytes=baos.toByteArray();
baos.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
}
public class test {
public SerializeUtils serializeUtils;
public Notification notification=new Notification();
@Test
public void main() {
notification.setId("wwwwwwwwwwwwwww");
notification.setDate(new Date());
notification.setContextPath("ppppppppppppppp");
notification.setPicPath("rrrrrrrrrrrrrrrrrrr");
byte[] bytes=serializeUtils.serialize(notification);
String res1=new String(bytes);
byte[] res1Tobytes=res1.getBytes();
String res2=String.valueOf(bytes);
byte[] res2Tobytes=res2.getBytes();
Notification notification1=(Notification)(serializeUtils.deSerialize(res1Tobytes));
Notification notification2=(Notification)(serializeUtils.deSerialize(res2Tobytes));
System.out.println("Finish");
}
}
转换结果如下:
这种方式的互转,虽然是类型对上了。但是实际上,数据却都丢失了,这种转换方式是错误的。
正确的转换方式是使用Java自带的Base64的API。
如下:
public class test {
public SerializeUtils serializeUtils;
public Notification notification=new Notification();
@Test
public void main() {
notification.setId("wwwwwwwwwwwwwww");
notification.setDate(new Date());
notification.setContextPath("ppppppppppppppp");
notification.setPicPath("rrrrrrrrrrrrrrrrrrr");
byte[] bytes=serializeUtils.serialize(notification);
String res= Base64.getEncoder().encodeToString(bytes);
Notification notification1=(Notification)(serializeUtils.deSerialize(Base64.getDecoder().decode(res)));
System.out.println("Finish");
}
}
可以看出,这种转换方式没有丢失实例对象的数据。