java 序列化为String无法反序列化

 最近要用到把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再进行反序列化很有可能因为编码的原因。

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值