对象正反序列化

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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.io.*;
import java.util.Base64;

/**
* 对象编码工具类
*/
public class ObjEncodeUtil {
public static String encodeBase64(Object object) {
if (object == null) {
return null;
}
ObjectOutputStream oos = null;
String result;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
result = Base64.getEncoder().encodeToString(bos.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

public static <T> T decodeBase64(String str) {
ObjectInputStream ois = null;
T result;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(str));
ois = new ObjectInputStream(bis);
result = (T) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}

class Bean{
int length;
double width;

public Bean() {
}

public Bean(int length, double width) {
this.length = length;
this.width = width;
}

public int getLength() {
return length;
}

public void setLength(int length) {
this.length = length;
}

public double getWidth() {
return width;
}

public void setWidth(double width) {
this.width = width;
}
}

Bean bean = new Bean(5,3.2);
String modelStr = ObjEncodeUtil.encodeBase64(bean);
Bean bean2 = ObjEncodeUtil.decodeBase64(modelStr);

1
2
3
4
5
6
import com.alibaba.fastjson.JSON;
ModelBean bean = new ModelBean();

String jsonResult = JSON.toJSONString(bean);
ModelBean bean2 = JSON.parseObject(jsonResult, ModelBean.class);