Java Jackson @JsonFormat Example

1. Introduction

Jackson's @JsonFormat annotation is used to customize the format of date, time and number values during serialization and deserialization. For instance, while dealing with Date objects, the default serialization might not always be to your liking. The @JsonFormat annotation allows you to define a pattern for such fields, ensuring the serialized format adheres to your requirements.

2. Example Steps

1. Create a Java class Event with a Date field.

2. Apply the @JsonFormat annotation to the Date field to customize its format.

3. Serialize an Event object to demonstrate the effect of the annotation.

3. Java Jackson @JsonFormat Example

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;

public class JacksonJsonFormatExample {

    public static void main(String[] args) throws Exception {
        // Create a new Event object
        Event event = new Event("Conference", new Date());

        // Initialize ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Serialize the Event object to JSON
        String jsonString = mapper.writeValueAsString(event);

        // Print the serialized JSON
        System.out.println(jsonString);
    }
}

class Event {
    private String name;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    private Date eventDate;

    // Constructor, getters, and setters
    public Event(String name, Date eventDate) {
        this.name = name;
        this.eventDate = eventDate;
    }

    public String getName() {
        return name;
    }

    public Date getEventDate() {
        return eventDate;
    }
}

Output:

{"name":"Conference","eventDate":"16-10-2023 02:15:30"}

4. Step By Step Explanation

The Event class in the provided code contains a Date field named eventDate. Using the @JsonFormat annotation, we customized the serialization format of this date to "dd-MM-yyyy hh:mm:ss". This means that, instead of the default ISO format or timestamp, the date will be serialized in our defined pattern.

When the Event object is serialized using Jackson's ObjectMapper, the eventDate field is formatted as per our custom format, resulting in a more human-readable date string in the serialized JSON output.


Comments