Jackson @JsonFormat Example

By Arvind Rai, June 11, 2018

On this page we will provide Jackson @JsonFormat example. @JsonFormat is used to decide how values of properties to be serialized. We can use @JsonFormat with Date properties to decide if date should be serialized in number or string format. Using @JsonFormat, timezone of date property can also be changed in serialization. @JsonFormat is also used to format Enum, Collection and Number in serialization. Here on this page we will provide @JsonFormat examples with Date properties and Java enum in serialization.

Technologies Used

@JsonFormat

@JsonFormat handles the serialization of Date, Enum, Collection and Number. @JsonFormat decides how values of properties to be serialized. Find some of the attributes of @JsonFormat annotation.
shape: Defines the structure to use for serialization, for example JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING.
pattern: Pattern used in serialization and deserializations. For date, pattern contains SimpleDateFormat compatible definition.
locale: Locale used in serialization. Default is system default locale.
timezone: TimeZone used in serialization. Default is system default timezone.
lenient: Useful in deserializations. It decides if lenient handling should be enabled or disabled.

JsonFormat.Shape.STRING

When we assign JsonFormat.Shape.STRING to shape attribute in @JsonFormat for a property, suppose Date type, then in serialization JSON will be string type in given pattern for that property.

@JsonFormat with Enum

@JsonFormat can be used with Java enum in serialization to change between index (number) and textual name (string). @JsonFormat is used at enum level and not at property level. By default enum properties are serialized with its textual name as string. We can change it to property index (starting from 0) using JsonFormat.Shape.NUMBER. Find the sample example.