Java – Use formatting to customize deserialization dates

Use formatting to customize deserialization dates… here is a solution to the problem.

Use formatting to customize deserialization dates

[“last_modified”])] with root cause
java.time.format.DateTimeParseException: Text ‘2018-06-06T13:19:53+00:00’ could not be parsed, unparsed text found at index 19

The inbound format is 2018-06-06T13:19:53+00:00
This is a strange format.

I tried the following:

public class XYZ {  
    @DateTimeFormat(pattern = "yyyy-MM-ddTHH:mm:ss+00:00", iso = ISO. DATE_TIME)
    private LocalDateTime lastModified;
}  

Solution

Nothing prevents you from creating your own deserializer. A very naïve example follows:

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss+00:00";

private final DateTimeFormatter formatter;

public LocalDateTimeDeserializer() {
        this.formatter = DateTimeFormatter.ofPattern(PATTERN);
    }

@Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return LocalDateTime.parse(p.getText(), formatter);
    }
}

The only thing you need to note is that you need to escape the “T” by putting single quotes around it.

With a deserializer, you can simply annotate the field like this:

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime dateTime;

Related Problems and Solutions