Dzmitry
Dzmitry

Reputation: 87

Jackson incorrectly deserialize Joda dates with custom date format

I'm trying to serialize and deserialize quite simple object with custom date format:

public class DateTimeTest {
    private static final String DATE_PATTERN = "yyyyMMdd";

    public static DateTime date = DateTime.now();

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JodaModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        ObjectWriter writer = mapper.writer();

        String str = writer.writeValueAsString(new Domain());
        System.out.println(str);

        ObjectReader reader = mapper.reader(Domain.class);
        Domain domain = reader.readValue(str);

        System.out.println(domain.getDate());
    }

    private static class Domain {
        @JsonFormat(pattern = DATE_PATTERN)
        private DateTime date;

        public Domain() {
            this.date = DateTime.now();
        }

        public DateTime getDate() {
            return date;
        }

        public void setDate(DateTime date) {
            this.date = date;
        }
    }
}

While executing main method I'm expecting to get something similar to:

"date":"20151117"
20151117

But unfortunately get the following:

{"date":"20151117"}
20151117-01-01T00:00:00.000+03:00 (year is incorrect)

Seems that Jackson ignores @JsonFormat annotation for objects deserialization and treat the string as date in ISO-8601 notation. Does anyone know the fix?

<jackson.version>2.5.4</jackson.version>
<jodatime.version>2.8.1</version>

UPDATE: If I change date pattern to "dd/MM/yyyy", then I even start getting error "IllegalArgumentException: Invalid format". So for sure Jackson ignores date pattern for deserialization.

Upvotes: 3

Views: 3962

Answers (4)

Dzmitry
Dzmitry

Reputation: 87

According to Jackson Release Notes support for Joda @JsonFormat(pattern=...) for deserialization was added only from 2.6.0 version.

Upvotes: 1

retroq
retroq

Reputation: 582

What is the problem? You got correct serialization and deserealization. The output "20151117-01-01T00:00:00.000+03:00" it is just the result of DateTime.toString().

Upvotes: 0

Heena
Heena

Reputation: 133

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SSSZ")

if exact pattern format not coming try this

http://wiki.fasterxml.com/JacksonFAQDateHandling

Set Jackson Timezone for Date deserialization

as am not sure even when u keeping formate den also result not obtained...go through the above link..it may help u

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37624

You need to add the shape to the JsonFormat

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_PATTERN)

Upvotes: 0

Related Questions