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