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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM