Reputation: 237
I have a class with one field:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "PST")
@JsonProperty("myDate")
private Date myDate;
When I try to deserialize a json string into an object:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("PST"));
ObjectNode node = objectMapper.createObjectNode();
node.put("myDate", "2016-11-06");
Object pojo = objectMapper.treeToValue(node, SomeClass.class);
It fails with this exception:
com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2016-11-06' (format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"): Unparseable date: "2016-11-06"
.
.
.
Caused by: java.lang.IllegalArgumentException: Failed to parse Date value '2016-11-06' (format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"): Unparseable date: "2016-11-06"
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:158)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:261)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:245)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:490)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:260)
Shouldn't the annotation, @JsonFormat be applicable for serialization only? At least thats what I understood by reading this FAQ: http://wiki.fasterxml.com/JacksonFAQDateHandling. Here I am unable to deserialize a json string into an object.
Even the JsonFormat java docs doesnt talk about it being used during deserialization: http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonFormat.html
Did I understand this feature wrong or am I doing something wrong in my code?
Upvotes: 3
Views: 12967
Reputation: 75914
No, the @JsonFormat annotation is applicable for both serailization and deserailization. So in de-serailization it is used to parse the datetime string to datetime object using DateFormat.parse method and in serailization the datetime object is formatted to date time string using DateFormat.format method.
For more info, take a look at the DateSerializer & DateDeserializers classes.
You should only use 'Z' if the value is a UTC time. So in your case change your date time format to "yyyy-MM-dd'T'HH:mm:ss.SSS" and pass the date time value as "2016-11-06T05:00:35.657". This will parse successfully.
Upvotes: 4