Can Jackson parse date-time values which aren't ISO-8601?

Viewed 175

I'm trying to get Jackson to parse the date-time values given to me by a particular API which I have no ability to change.

So I'm giving it a custom pattern:

public class Problem {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());

        String json = "{\"posted_at\":\"Mon, 14 Oct 2019 13:00:00 +0900\"}";
        Model model = mapper.readValue(json, Model.class);
        System.out.println(model.posted_at);
    }

    public static class Model {
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "E, d MMM yyyy HH:mm:ss XX")
        public ZonedDateTime posted_at;
    }
}

I get this exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon, 14 Oct 2019 13:00:00 +0900' could not be parsed at index 0

It seems like it's failing at index 0, but I don't understand why because for the day of the week format pattern "E", it seems like "Mon" should be the correct value.

Tried so far:

  • Setting DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE:

    mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false)
    

    Result: same exception.

  • Adding Jdk8Module:

    ObjectMapper mapper = new ObjectMapper()
       .registerModule(new Jdk8Module())
       .registerModule(new JavaTimeModule()); 
    

    Result: same exception.

1 Answers

Jackson has worked for a long time with Joda DateTime and from your error message it seems you are using Java.DateTime to add support for Java dateTime you need to add some extra dependencies "jackson-datatype-jdk8" see https://github.com/FasterXML/jackson-modules-java8

<dependency>
 <groupId>com.fasterxml.jackson.datatype</groupId>
 <artifactId>jackson-datatype-jdk8</artifactId> 
</dependency>

Then you set ADJUST_DATES_TO_CONTEXT_TIME_ZONE

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false)

Then you add the new modules

// Up to Jackson 2.9: (but not with 3.0)
ObjectMapper mapper = new ObjectMapper()
   .registerModule(new Jdk8Module())
   .registerModule(new JavaTimeModule()); 
Related