简体   繁体   中英

Jackson ObjectMapper not accepting all dateFormats

I am trying to set a custom date Format to the Jackson Object mapper(I am using Jackson-databind-2.8.x ) so that it can parse the incoming JSON date in a specific format. A date format without seconds part works fine, but when i add seconds to it ; it seems to fail.

Format that works

Date format: yyyy-MM-dd HH:mmZ

Example of date that gets parsed fine : 2019-09-01 15:00+0000

Setting date format to object mapper:

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mmZ"));

Format that does not work

Date format : yyyy-MM-dd HH:mm:ssZ

Example date : 2019-09-01 15:00:00+0000

Setting date format to object mapper:

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"));

Exception :

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: 
Can not deserialize value of type java.util.Date from String "2019-09-01 15:00:00+0000": not a valid representation (error: Failed to parse Date value '2019-09-01 15:00:00+0000': Unparseable date: "2019-09-01 15:00:00+0000")

I have verified that above is a proper simple date format as below code works fine:

import java.text.SimpleDateFormat;

public class TestDF {

    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");

        String date = "2019-09-01 15:00:00+0000";

        System.out.println(format.parse(date));
    }
}

You should look more closely at your code:

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mmZ"));

vs

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");

Which are two different formats.

Should be:

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"));

Note the addition for :ss

which is indeed the format for the given String.

EDIT

This test works (using Jackson 2.8.0)

public class FormatTest {

    @Test
    public void testFormat() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
        String date = "2019-09-01 15:00:00+0000";
        Date parse = sdf.parse(date);
        String json = "{\"date\" : \"" + date + "\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(sdf);
        ClassWithDate cwd = objectMapper.readValue(json, ClassWithDate.class);
        Assert.assertEquals(parse, cwd.date);
    }

    private static class ClassWithDate {
        public Date date;
    }

}

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