You can command Jackson to serialize Date fields in a precise string format in JSON using @JsonFormat with pattern in your model class.
Example:
publicclassEvent{
// No need for a calendar when you have @JsonFormat!@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date eventDate;
// getters and setters}
This small trick powers Jackson to format dates as "yyyy-MM-dd HH:mm:ss" in your JSON output.
Dealing with Timezones
At times, to fit your need, you might want to set your desired timezone with the timezone attribute:
In intricate date formatting scenarios, you can rise above by creating custom serializers and deserializers. This bespoke approach paves the way to having full control over how dates are processed before being mapped to object members.
// Because 'Simple' in SimpleDateFormat is for 'brain-fryingly intricate'publicclassCustomDateSerializerextendsStdSerializer<Date> {
privatestaticfinal SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
publicCustomDateSerializer(){
this(null);
}
publicCustomDateSerializer(Class<Date> t){
super(t);
}
@Overridepublicvoidserialize(Date value, JsonGenerator gen, SerializerProvider arg2)throws IOException {
gen.writeString(formatter.format(value));
}
}
Tip: Hook your custom serializer class with @JsonSerialize annotation:
@JsonSerialize(using = CustomDateSerializer.class)private Date eventDate;
Pro tip: For deserialization, JsonDeserializer comes to the rescue:
Boldly integrate your deserializer using @JsonDeserialize:
@JsonDeserialize(using = CustomDateDeserializer.class)private Date eventDate;
Global Date Format: For the Greater Good
For times when you prefer to wield global power, conflict the ObjectMapper:
// You want global changes? Apply hereObjectMapper mapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
mapper.setDateFormat(sdf);
This paragon now sets the standard date format for all Date serialization and deserialization processes in your domain.
Visualization
Let's put on our goggles and visualize custom date formatting in Java with Jackson as a journey through time: