0

My application is supposed to receive a JSON message through an HTTP request and I'm using a custom deserializer to map the LocalDateTime properties of some of my classes. But, when I receive the information through JsonParser the month is offset by -1.

E.g. The message that is sent is: "2020-10-12T10:20:00.000Z" and the message that is inside the JsonParser is: "2020-09-12T10:20:00.000Z".

I'm using Jackson 2.9.6 and SpringBoot 2.1.3. Any ideas what could be the cause of this?

@Override
public LocalDate deserialize(final JsonParser p, final DeserializationContext ctxt)
        throws IOException {
    final String date = p.readValueAs(String.class);
    if (date == null) {
        return null;
    }

    try {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        ZonedDateTime dateToParse = ZonedDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);
        return dateToParse.toLocalDate();
    } catch (final DateTimeParseException ex) {
        LOGGER.error(ex.getMessage());
        return null;
    }
}

My issue is at "final String date = p.readValueAs(String.class)". p contains the value that is received and its Month is offset by -1.

M. Chris
  • 161
  • 2
  • 14

3 Answers3

0

Fix your date offset by doing something like this:

// "2020-00-01'T'12:00:00.00'0'"
String date = p.readValueAs(String.class); 
int month = Integer.parseInt(date.substring(5, 7)) + 1;
date = date.substring(0, 5) + (month < 10 ? "0" : "") + month + date.substring(7);

You are not using the DateTimeFormatter you are creating, you're using the ISO_DATE_TIME constant instead.

Try using the one you are creating:

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ZonedDateTime dateToParse = ZonedDateTime.parse(date, df);
mikeb
  • 10,578
  • 7
  • 62
  • 120
  • My issue is at "final String date = p.readValueAs(String.class)". p contains the value that is received and its Month is offset by -1. – M. Chris Jan 23 '20 at 12:43
  • @M.Chris: Your question would be clearer if you'd remove all the rest of the code then... and ideally provide a [mcve]. – Jon Skeet Jan 23 '20 at 13:28
0

add below in the properties spring.datasource.url= jdbc:mysql://Schema:YourDBusername and DbPssword?useSSL=false&useLegacyDatetimeCode=false&zeroDateTimeBehavior=convertToNull

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS= false spring.jackson.time-zone= UTC

rohithd
  • 147
  • 1
  • 6
0

You don't need a custom deserializer. You can annotate your property with date format as follows

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
public ZonedDateTime getTime() {
    return time;
}

And that should do the trick. See the answer to this question: Spring Data JPA - ZonedDateTime format for json serialization

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36