Java序列化对象-字符串转换

 1 package com.test;
 2 
 3 import com.alibaba.fastjson.JSON;
 4 import org.junit.Test;
 5 
 6 import java.io.ByteArrayInputStream;
 7 import java.io.ByteArrayOutputStream;
 8 import java.io.ObjectInputStream;
 9 import java.io.ObjectOutputStream;
10 
11 public class SerializeTest {
12     @Test
13     public void Test()throws Exception{
14         AgencyVoInfo dept = new AgencyVoInfo();
15         dept.setAgencyCode("1");
16         dept.setAgencyName("2");
17         dept.setBranchCode("3");
18         dept.setId(1);
19         dept.setSerialNo(1);
20         String objectStr = serializeObject(dept);
21         System.out.println(objectStr);
22         AgencyVoInfo dept2 = (AgencyVoInfo)stringSerializeObject(objectStr);
23         System.out.println(JSON.toJSON(dept2));
24     }
25     /**
26      * 对象序列化为字符串
27      * @param object
28      * @return
29      */
30     public static String serializeObject(Object object)throws Exception{
31         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
32         ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
33         out.writeObject(object);
34                                                                   //必须是ISO-8859-1
35         String objectStr = byteArrayOutputStream.toString("ISO-8859-1");
36         out.close();
37         byteArrayOutputStream.close();
38         return objectStr;
39     }
40 
41     /**
42      * 字符串序列化为对象
43      * @param objectStr
44      * @return
45      * @throws Exception
46      */
47     public static Object stringSerializeObject(String objectStr)throws Exception{
49         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectStr.getBytes("ISO-8859-1"));
50         ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
51         Object object =  objectInputStream.readObject();
52         objectInputStream.close();
53         byteArrayInputStream.close();
54         return object;
55     }
56 }

 

posted on 2018-02-24 12:20 【cosmo】 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值