@JsonSerialize
@JsonSerialize is used to indicate a custom serializer will be used to marshall the entity.
Let's look at a quick example - we're going to use @JsonSerialize to serialize the eventDate property with a CustomDateSerializer:
public class Event {
public String name;
@JsonSerialize(using = CustomDateSerializer.class)
public Date eventDate;
public Event() {
}
public Event(String name, Date eventDate) {
this.name = name;
this.eventDate = eventDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getEventDate() {
return eventDate;
}
public void setEventDate(Date eventDate) {
this.eventDate = eventDate;
}
}
Here's the simple custom Jackson serializer:
public class CustomDateSerializer extends StdSerializer<Date> {
private static SimpleDateFormat format =
new SimpleDateFormat("dd-MM-yyyy hh:mm:ss呵呵");
public CustomDateSerializer() {
this(null);
}
protected CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
jgen.writeString(format.format(value));
}
}
Let's use these in a test:
public class CustomDateSerializer extends StdSerializer<Date> {
private static SimpleDateFormat format =
new SimpleDateFormat("dd-MM-yyyy hh:mm:ss呵呵");
public CustomDateSerializer() {
this(null);
}
protected CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
jgen.writeString(format.format(value));
}
}
/**
output: {"name":"dengyi","eventDate":"01-09-2017 08:53:25呵呵"}
*/