cosmo

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 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】  阅读(7090)  评论(0编辑  收藏  举报