jackson csv export setDateFormat ignored?

69 views Asked by At

I'm trying to export a custom date format with Jackson 2.15.2 CsvMapper. But I get the LocalDate#toString, I assume my test code is complete, what am I missing?

Complete test class, the log output is

org.opentest4j.AssertionFailedError: 2023-12-04 does not contain 04.12.2023 ==> Expected:true Actual:false

class CsvExportDateFormatTest
{
    @Test
    void csvExportDateFormatTest() throws IOException
    {
        LocalDate now = LocalDate.now();

        String pattern = "dd.MM.yyyy";
        String formatted = DateTimeFormatter.ofPattern(pattern)
                .format(now);

        CsvMapper mapper = CsvMapper.builder()
                .addModule(new JavaTimeModule())
                .configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, false)
                .configure(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING, true)
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                .build();
        mapper.setDateFormat(new SimpleDateFormat(pattern));

        List<MyClass> l = new ArrayList<>();
        l.add(new MyClass(now));
        CsvSchema schema = mapper.schemaFor(MyClass.class);
        StringWriter sw = new StringWriter();
        mapper.writer(schema)
                .writeValue(sw, l);

        Assertions.assertTrue(sw.toString()
                .contains(formatted), sw + " does not contain " + formatted);
    }

    static class MyClass
    {
        private LocalDate now;

        public MyClass(LocalDate now)
        {
            this.now = now;
        }

        public LocalDate getNow()
        {
            return now;
        }

        public void setNow(LocalDate now)
        {
            this.now = now;
        }
    }
}
1

There are 1 answers

0
Gunnar On BEST ANSWER

Ok, I removed

.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)

and

mapper.setDateFormat(new SimpleDateFormat(pattern));

and added

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")

to MyClass#now

and it works.