This repository was archived by the owner on Feb 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializationHelper.java
More file actions
82 lines (67 loc) · 2.58 KB
/
Copy pathSerializationHelper.java
File metadata and controls
82 lines (67 loc) · 2.58 KB
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
package org.mai.dep810.rest_api_io_lesson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import java.io.*;
public class SerializationHelper<T extends Serializable> {
Class<T> serialazationType;
public SerializationHelper(Class<T> serialazationType) {
this.serialazationType = serialazationType;
}
private Logger log = Logger.getLogger(getClass());
ObjectMapper mapper = new ObjectMapper();
/*
Необходимо десереализовать объект из файла по указанному пути
*/
public T loadFromFile(String path) {
T res = null;
try (InputStream in = new FileInputStream(path)) {
ObjectMapper mapper = new ObjectMapper();
res = mapper.readValue(in, serialazationType);
}
catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
/*
Необходимо сохранить сереализованный объект в файл по указанному пути
*/
public boolean saveToFile(String path, T toSave) {
boolean res = false;
// "try() - try with resources" в конструктор передается объект Closeable/Flushable
// "So if you use the try-with statement your code gets a lot cleaner and most importantly: resource will always be closed
// вместо того, чтобы городить finally/try блоки для close() и соотв проверки на null
try(OutputStream out = new FileOutputStream(path)) {
writeJsonToStream(out, toSave);
res = true;
}
catch (IOException ignored) {
}
return res;
}
public String convertToJsonString(T toConvert) {
try {
String json = mapper.writeValueAsString(toConvert);
return json;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public void writeJsonToStream(OutputStream output, T toWrite) {
try {
mapper.writeValue(output, toWrite);
} catch (IOException e) {
e.printStackTrace();
}
}
public T parseJson(String json) {
try {
return mapper.readValue(json, serialazationType);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}