2

I am getting the following error on Date deserialization in Java:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "22-09-2020T05:08:05+0000": not a valid representation (error: Failed to parse Date value '22-09-2020T05:08:05+0000': Cannot parse date "22-09-2020T05:08:05+0000": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

My input date is in this format 22-09-2020T05:08:05+0000

I am using

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'HH:mm:ssZ")
    OffsetDateTime lastAnalysisDate;

How to resolve this error ? Inspite of using custom JsonFormat, the error message says it is not of the standard data types.

I am using the date formatter validation tool online https://javadevtools.com/simpledateformat

And the format I specified is valid as per this evaluation tool

Svirin
  • 564
  • 1
  • 7
  • 20
  • You need to register `JavaTimeModule`. See: [Problem with deserialization of LocalDateTime in Junit test](https://stackoverflow.com/questions/55107588/problem-with-deserialization-of-localdatetime-in-junit-test), [Jackson deserialize elasticsearch long as LocalDateTime with Java 8](https://stackoverflow.com/questions/57098784/jackson-deserialize-elasticsearch-long-as-localdatetime-with-java-8), [Jackson Serialize Instant to Nanosecond Issue](https://stackoverflow.com/questions/56345200/jackson-serialize-instant-to-nanosecond-issue) – Michał Ziober Oct 12 '20 at 17:44

1 Answers1

0

The issue is very likely consisting not in the date format but in the configuration of the ObjectMapper where you have to register JavaTimeModule to process classes from java.time package:

Example:

public class TestOffsetDate {
    @Getter
    @Setter
    static class D {
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'HH:mm:ssZ")
        private OffsetDateTime lastAnalysisDate;
    }

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule()); // <--- this is required

        String json = "{\"lastAnalysisDate\":\"22-09-2020T05:08:05+0000\"}";
        D d = mapper.readValue(json, D.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(d));
    }
}

Parsing of the sample JSON succeeds, the following output is printed:

{
  "lastAnalysisDate" : "22-09-2020T05:08:05+0000"
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42