/
JsonHelper.java
83 lines (73 loc) · 1.55 KB
/
JsonHelper.java
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
package app.utils;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Stefano Crespi
*/
public class JsonHelper {
/**
* Deserializes object from JSON
*
* @param json
* @return the created map
* @throws IOException
*/
public static Map<String, Object> fromJson(String json)
throws IOException
{
return new ObjectMapper().readValue(json, HashMap.class);
}
/**
* Builds a list form JSON
*
* @param json
* @return the created list
* @throws IOException
*/
public static List<Map<String, Object>> fromJsonToList(String json)
throws IOException
{
return new ObjectMapper().readValue(json, List.class);
}
/**
* Serializes object from JSON
*
* @param object
* @return the json representation
*/
public static String toJson(Object object) {
try {
return new ObjectMapper().writeValueAsString(object);
} catch (IOException ex) {
// Log exception
return null;
}
}
/**
* @param json
* @return the created map
*/
public static Map toMap(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, Map.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @param json
* @return the array of created maps
*/
public static Map[] toMaps(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, Map[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}