简体   繁体   中英

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

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.

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()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM