custom deserializing a date with format

Jim :

["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
It's a weird format.

I have tried the following:

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

There is nothing stopping you from creating your own deserializer. A very naive example could be the following:

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 notice is that you'll need to escape the 'T' by adding single quote around it.

With the deserializer in place you can simply annotate the field like so:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98689&siteId=1