@JsonSerialize: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=Internal= * Jackson =Overview=") |
|||
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=External= | |||
* http://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.9.7/com/fasterxml/jackson/databind/annotation/JsonSerialize.html | |||
=Internal= | =Internal= | ||
Line 4: | Line 8: | ||
=Overview= | =Overview= | ||
The annotation allows to control serialization to JSON on a field-by-field basis. The fields need to be annotated as follows: | |||
<syntaxhighlight lang='java'> | |||
@JsonSerialize(using = MyDateSerializer.class) | |||
private Date timestamp; | |||
</syntaxhighlight> | |||
The serializer class should be provided: | |||
<syntaxhighlight lang='java'> | |||
public class MyDateSerializer<Date> extends JsonSerializer<Date> { | |||
@Override | |||
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException { | |||
DateFormat f = new SimpleDateFormat("MM/dd"); | |||
String s = f.format(value); | |||
gen.writeString(s); | |||
} | |||
} | |||
</syntaxhighlight> | |||
=Example= | |||
{{External|[https://github.com/ovidiuf/playground/tree/master/json/jackson/annotations/%40JsonSerialize-for-Date @JsonSerialize Playground Example]}} |
Latest revision as of 18:11, 14 November 2018
External
Internal
Overview
The annotation allows to control serialization to JSON on a field-by-field basis. The fields need to be annotated as follows:
@JsonSerialize(using = MyDateSerializer.class)
private Date timestamp;
The serializer class should be provided:
public class MyDateSerializer<Date> extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
DateFormat f = new SimpleDateFormat("MM/dd");
String s = f.format(value);
gen.writeString(s);
}
}