I need to set format for class' date serialization.
I have the version of Jackson, which doesn't have @JsonFormat. That's Why I wrote custom class:
public class CDJsonDateSerializer extends JsonSerializer<Date>{
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String dateString = dateFormat.format(date);
jsonGenerator.writeString(dateString);
}
}
And used it:
@JsonSerialize(using = CDJsonDateSerializer.class)
private Date startDate;
But, I have another fields which have different date's formats and I don't want to create another classes for serialization. Can I add all needed formats like constants to CDJsonDateSerializer class and set needed format with annotation @JsonSerialize
?
Something like this:
@JsonSerialize(using = CDJsonDateSerializer.class, CDJsonDateSerializer.FIRST_FORMAT)
.
AFTER THE ANSWER BELOW:
It works after some corrections. I've changed the way of getting annotation in createContextual method:
@Override
public JsonSerializer createContextual(SerializationConfig serializationConfig, BeanProperty beanProperty) {
return new CustomDateSerializer(beanProperty.getAnnotation(JsonDateFormat.class).value());
}
And I've added @JacksonAnnotation to my created new annotation JsonDateFormat:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonDateFormat {
String value();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…