1
|
package {{invokerPackage}};
|
2
|
|
3
|
import com.fasterxml.jackson.annotation.*;
|
4
|
import com.fasterxml.jackson.databind.*;
|
5
|
import com.fasterxml.jackson.datatype.joda.*;
|
6
|
|
7
|
import java.io.IOException;
|
8
|
|
9
|
{{>generatedAnnotation}}
|
10
|
public class JSON {
|
11
|
private ObjectMapper mapper;
|
12
|
|
13
|
public JSON() {
|
14
|
mapper = new ObjectMapper();
|
15
|
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
16
|
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
17
|
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
18
|
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
19
|
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
20
|
mapper.registerModule(new JodaModule());
|
21
|
}
|
22
|
|
23
|
/**
|
24
|
* Serialize the given Java object into JSON string.
|
25
|
*/
|
26
|
public String serialize(Object obj) throws ApiException {
|
27
|
try {
|
28
|
if (obj != null)
|
29
|
return mapper.writeValueAsString(obj);
|
30
|
else
|
31
|
return null;
|
32
|
} catch (Exception e) {
|
33
|
throw new ApiException(400, e.getMessage());
|
34
|
}
|
35
|
}
|
36
|
|
37
|
/**
|
38
|
* Deserialize the given JSON string to Java object.
|
39
|
*
|
40
|
* @param body The JSON string
|
41
|
* @param returnType The type to deserialize inot
|
42
|
* @return The deserialized Java object
|
43
|
*/
|
44
|
public <T> T deserialize(String body, TypeRef returnType) throws ApiException {
|
45
|
JavaType javaType = mapper.constructType(returnType.getType());
|
46
|
try {
|
47
|
return mapper.readValue(body, javaType);
|
48
|
} catch (IOException e) {
|
49
|
if (returnType.getType().equals(String.class))
|
50
|
return (T) body;
|
51
|
else
|
52
|
throw new ApiException(500, e.getMessage(), null, body);
|
53
|
}
|
54
|
}
|
55
|
}
|