Skip to content

Commit db06188

Browse files
authored
Merge pull request #169 from dimaa6/168-static-gson
Made Gson static to avoid creating it for each (de)serialization requ…
2 parents 791aa3c + a5ea9f8 commit db06188

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

OCPP-J/src/main/java/eu/chargetime/ocpp/JSONCommunicator.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -77,38 +77,37 @@ public JSONCommunicator(Radio radio) {
7777
super(radio);
7878
}
7979

80-
private class ZonedDateTimeSerializer implements JsonSerializer<ZonedDateTime> {
80+
private static class ZonedDateTimeSerializer implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
8181

8282
@Override
8383
public JsonElement serialize(
8484
ZonedDateTime zonedDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
8585
return new JsonPrimitive(zonedDateTime.format(DateTimeFormatter.ISO_INSTANT));
8686
}
87-
}
88-
89-
public class ZonedDateTimeDeserializer implements JsonDeserializer<ZonedDateTime> {
9087

9188
@Override
9289
public ZonedDateTime deserialize(
93-
JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
94-
throws JsonParseException {
90+
JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
91+
throws JsonParseException {
9592
return ZonedDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString());
9693
}
9794
}
9895

96+
private static Gson gson;
97+
98+
static {
99+
GsonBuilder builder = new GsonBuilder();
100+
builder.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeSerializer());
101+
gson = builder.create();
102+
}
103+
99104
@Override
100105
public <T> T unpackPayload(Object payload, Class<T> type) throws Exception {
101-
GsonBuilder builder = new GsonBuilder();
102-
builder.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeDeserializer());
103-
Gson gson = builder.create();
104106
return gson.fromJson(payload.toString(), type);
105107
}
106108

107109
@Override
108110
public Object packPayload(Object payload) {
109-
GsonBuilder builder = new GsonBuilder();
110-
builder.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeSerializer());
111-
Gson gson = builder.create();
112111
return gson.toJson(payload);
113112
}
114113

0 commit comments

Comments
 (0)