If you want to read and output json.
Define a custom deserialiser as follows:
class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDateTime.parse(json.getAsString(),
DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss").withLocale(Locale.ENGLISH));
}
}
Define a custom serialiser as follows;
class LocalDateTimeSerializer implements JsonSerializer < LocalDateTime > {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDateTime));
}
}
String them together like this (for calling from static main):
private static Gson buildGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
return gson;
}
Improve the definition of TestJava.toString() like this:
@Override
public String toString() {
return "TestJava [service=" + service + ", userIP=" + userIP + ", startDateTime=" + formatter.format(startDateTime) + "]";
}
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
Use it like this:
public static void main(String[] args) {
Gson gson = buildGson();
String inputValue = "{\"service\": 2,\"userIP\": \"10.1.1.2.3\",\"startDateTime\": \"20230321 12:55:44\"}";
TestJava object = gson.fromJson(inputValue, TestJava.class);
String outputValue = gson.toJson(object);
System.out.println("Serialised: " + outputValue);
System.out.println("toString: " + object);
}
Output:
Serialised: {
"service": 2,
"userIP": "10.1.1.2.3",
"startDateTime": "2023-Mar-21 12:55:44"
}
toString: TestJava [service=2, userIP=10.1.1.2.3, startDateTime=2023-Mar-21 12:55:44]