chenjiahe
2023-09-01 2e06d10f39d8bbdeae8a8da99f3d94ed027df24c
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import org.springframework.stereotype.Component;
4
5 import java.io.*;
6 import java.net.URLDecoder;
7 import java.net.URLEncoder;
8
9 /**
10  * @PackageName com.hx.util
11  * @ProjectName hx-parent
12  * @Author: ChenJiaHe
13  * @Date: Create in 16:52 2019/7/22
14  * @Description:
15  * @Copyright Copyright (c) 2019, hx01@163.com All Rights Reserved.
16  */
17 @Component
18 public class SerializeUtil<E> {
19
20     public String serialize(E object) {
21         ObjectOutputStream oos = null;
22         ByteArrayOutputStream baos = null;
23         try {
24             baos = new ByteArrayOutputStream();
25             oos = new ObjectOutputStream(baos);
26             oos.writeObject(object);
27
28             String str = baos.toString("ISO-8859-1");
29             return URLEncoder.encode(str, "UTF-8");
30         } catch (Exception e) {
31             e.printStackTrace();
32         } finally {
33             try {
34                 baos.close();
35                 oos.close();
36             } catch (Exception e) {
37                 e.printStackTrace();
38             }
39         }
40         return null;
41     }
42
43     @SuppressWarnings("unchecked")
44     public E unserialize(String serializeStr) {
45         String readStr = "";
46         if (serializeStr == null || "".equals(serializeStr)) {
47             return null;
48         }
49         try {
50             readStr = URLDecoder.decode(serializeStr, "UTF-8");
51         } catch (Exception e) {
52             e.printStackTrace();
53         }
54         ObjectInputStream ois = null;
55         InputStream bais = null;
56         try {
57             bais = new ByteArrayInputStream(readStr.getBytes("ISO-8859-1"));
58             ois = new ObjectInputStream(bais);
59             return (E) ois.readObject();
60         } catch (Exception e) {
61             e.printStackTrace();
62         } finally {
63             try {
64                 ois.close();
65                 bais.close();
66             } catch (Exception e) {
67                 e.printStackTrace();
68             }
69         }
70         return null;
71     }
72 }