JsonAttributeConverter.java
2.36 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
package fi.codecrew.moya.model.converters;
import java.io.StringReader;
import java.sql.SQLException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.postgresql.util.PGobject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Converter(autoApply = true)
public class JsonAttributeConverter implements AttributeConverter<JsonObject, PGobject> {
private static final Logger log = LoggerFactory.getLogger(JsonAttributeConverter.class);
/**
* JsonObject -> PGobject
*/
public PGobject convertToDatabaseColumn(JsonObject jsonObject) {
//log.info("Converting JsonObject to PGobject. Original JsonObject: {}", jsonObject);
PGobject pgObject = new PGobject();
pgObject.setType("json");
try {
if (jsonObject != null) {
pgObject.setValue(jsonObject.toString());
} else {
pgObject.setValue(null);
}
} catch (SQLException e) {
log.warn("PGobject.setValue() threw an exception. Should not happen. Something is wrong.", e);
}
// log.info("Converted JsonObject to PGobject: {}", pgObject);
return pgObject;
}
/**
* PGobject -> JsonObject
*/
public JsonObject convertToEntityAttribute(PGobject pgObject) {
// log.info("Converting PGobject to JsonObject. Original PGobject: {}", pgObject);
// Convert null values to empty object
if (pgObject == null) {
// log.info("PGobject was null. Retruning an empty JsonObject.");
return Json.createObjectBuilder().build();
}
// Correct type of object?
if (pgObject.getType().equals("json") == false) {
log.error("Expected to be converting JSON column, but got PGobject whose type is not json but {}", pgObject.getType());
throw new RuntimeException("Expected JSON object from database");
}
// Read the value as JSON
String stringValue = pgObject.getValue();
// We must test for "null" because pgObject.getValues() seems to return "null" for null :)
if (stringValue != null && !stringValue.toLowerCase().equals("null")) {
JsonReader jsonReader = Json.createReader(new StringReader(stringValue));
JsonObject jsonObject = jsonReader.readObject();
// log.info("Converted PGobject to JsonObject: {}", jsonObject);
return jsonObject;
} else {
log.info("Null value. Returning empty JsonObject");
return Json.createObjectBuilder().build();
}
}
}