I am using jackson library and I have came across a situation where I want to disable @JsonFormat annotation using objectmapper while serialization/deserialization.
My Api code is in 3rd party library so i can't remove/add any annotation, so objectMapper is the only choice.
Api class:
public class ApiClass {
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private DateTime time;
}
My code:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(Include.NON_ABSENT);
objectMapper.registerModule(new JodaModule());
objectMapper.registerModule(new JavaTimeModule());
String str = " {\"time\": \"2012-05-01\"}";
ApiClass msg = objectMapper.readValue(str, ApiClass.class);
I want this conversion to happen successfully.
Currently I am getting: com.fasterxml.jackson.databind.JsonMappingException: Invalid format: "2012-05-01" is too short
Please help me here.
Thanks in advance
Below is the code that will disable JsonFormat specifically:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(Include.NON_ABSENT);
objectMapper.registerModule(new JodaModule());
objectMapper.registerModule(new JavaTimeModule());
objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
protected <A extends Annotation> A _findAnnotation(final Annotated annotated,
final Class<A> annoClass) {
if (!annotated.hasAnnotation(JsonFormat.class)) { //since we need to disable JsonFormat annotation.
return super._findAnnotation(annotated, annoClass);
}
return null;
}
});
String str = " {\"time\": \"2012-05-01\"}";
ApiClass msg = objectMapper.readValue(str, ApiClass.class);
System.out.println(objectMapper.writeValueAsString(msg ));
In case we need to disable multiple annotations(JsonFormat, JsonUnWrapped) then:
replace:
if (!annotated.hasAnnotation(JsonFormat.class)) {
with:
if (!annotated.hasOneOf(new Class[] {JsonFormat.class, JsonUnwrapped.class})) {
Thanks all.