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 }

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/18553.html

(0)
上一篇 2021年7月19日 21:14
下一篇 2021年7月19日 21:14

相关推荐

发表回复

登录后才能评论