Jackson deserialize LocalDateTime

2.6k views Asked by At

I have a time field value like below :

2020-10-01T15:30:27.4394205+03:00

I can't figure it out how to represent as date Format.

i need to deserialize it to LocalDateTime field.

I have tried like this;

   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
    private LocalDateTime timestamp;

but it doesn't work. How can i deserialize it? I am using spring boot by the way. And this value coming to rest controller request body.

3

There are 3 answers

1
Arvind Kumar Avinash On BEST ANSWER

Replace the pattern as pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME

Your date-time string is already in the format specified by DateTimeFormatter.ISO_OFFSET_DATE_TIME which is the default format used by OffsetDateTime#parse.

Demo:

import java.time.LocalDateTime;
import java.time.OffsetDateTime;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "2020-10-01T15:30:27.4394205+03:00";

        // Parse the date-time string into OffsetDateTime
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
        System.out.println(odt);

        // LocalDateTime from OffsetDateTime
        LocalDateTime ldt = odt.toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2020-10-01T15:30:27.439420500+03:00
2020-10-01T15:30:27.439420500
2
Rony Nguyen On
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX")
private LocalDateTime timestamp;
0
user404 On

Write a custom deserializer for it:

@Log4j2
public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

 public CustomLocalDateTimeDeserializer() {
    this(null);
}
    private CustomLocalDateTimeDeserializer(Class<LocalDateTime> t) {
        super(t);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String date = jsonParser.getText();
        try {
            return LocalDateTime.parse(date);
        } catch (Exception ex) {
            log.debug("Error while parsing date: {} ", date, ex);
            throw new RuntimeException("Cannot Parse Date");
        }
    }
}

Now, use the deserializer:

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
 @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
 private LocalDateTime timestamp;

Similarly, if you need to serialize it, write a custom serializer too.