Nitin Bansal
Nitin Bansal

Reputation: 3030

Jackson ObjectMapper not respecting configured date time format

There's high probability I'm missing something, but, I'm unable to configure object mapper to use given date-time format. Parsing date-time string using same date formatter (that is used to configure object mapper) successfully parses the same date-time string. Here's relevant code.

    String eventTimeString = "2018-06-13 20:22:00";
    String jsonString = "{\"event_time\":\""+eventTimeString+"\"}";

    // configure date formatter
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    // configure object mapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(sdf);

    // parse json string using configured object mapper
    Map<String, Object> jsonDataMap = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});

    // print event time class as parsed by object mapper
    System.out.println("event time class: " + (jsonDataMap.get("event_time").getClass().getName()));

    // test parsing date time field
    System.out.println(sdf.parse(eventTimeString));

The output that I get is:

event time class: java.lang.String
Thu Jun 14 01:52:00 IST 2018

What am I doing wrong here?

Thanks...

Upvotes: 2

Views: 2683

Answers (1)

Oz Molaim
Oz Molaim

Reputation: 2136

You missed a minor thing. You should resolve the type to Map<String, Date> instead of Map<String, Object> as follow:

Map<String, Date> jsonDataMap = mapper.readValue(jsonString, new TypeReference<Map<String, Date>>() {});

Upvotes: 1

Related Questions