最近要用到把java对象序列化为String字符在网络进行传输,结果发现了一点问题
下面是改好的可以用的代码
/**
* 序列化对象为String字符串
* @param o Object
* @return String
* @throws Exception
*/
public static String writeObject(Object o) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
oos.close();
bos.close();
return new BASE64Encoder().encode(bos.toByteArray());
}
/**
* 反序列化字符串为对象
* @param object String
* @return
* @throws Exception
*/
public static Object readObject(String object) throws Exception{
ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(object));
ObjectInputStream ois = new ObjectInputStream(bis);
Object o = ois.readObject();
bis.close();
ois.close();
return o;
}
这段代码唯一的不同是先对序列化后的进行BASE64编码,然后再转化为String.
初部分析,不能直接把字节转化为String再进行反序列化很有可能因为编码的原因。