Java Jackson @JsonSerialize Example

1. Introduction

Jackson's @JsonSerialize annotation is used to specify a custom serializer for a type or a property, allowing you to control the serialization of an object to JSON. This is especially useful when you need to customize the default serialization process or if you have special requirements for the JSON output.

2. Example Steps

1. Define a DateSerializer class that extends JsonSerializer to customize the serialization of java.util.Date.

2. Create a User class with a birthDate field.

3. Annotate the birthDate field with @JsonSerialize and specify the custom DateSerializer.

4. Serialize an instance of the User class.

5. Observe the custom formatted date in the serialized JSON string.

3. Java Jackson @JsonSerialize Example

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.text.SimpleDateFormat;
import java.util.Date;

public class JacksonJsonSerializeExample {

    public static void main(String[] args) throws Exception {
        // Initialize ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Create an instance of User
        User user = new User("Alice", new Date());

        // Serialize the User instance to JSON string
        String serializedUser = mapper.writeValueAsString(user);

        // Print the serialized string
        System.out.println(serializedUser);
    }

    static class User {
        private String name;

        @JsonSerialize(using = DateSerializer.class)
        private Date birthDate;

        public User(String name, Date birthDate) {
            this.name = name;
            this.birthDate = birthDate;
        }

        // Standard getters and setters
    }

    static class DateSerializer extends JsonSerializer<Date> {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }
}

Output:

{"name":"Alice","birthDate":"2023-10-17"}

4. Step By Step Explanation

In the User class, the birthDate field is annotated with @JsonSerialize and specifies DateSerializer as its custom serializer. The DateSerializer class extends JsonSerializer and overrides the serialize method. Inside this method, we convert the Date object into a custom string format ("yyyy-MM-dd"). As a result, when the User object is serialized, the birthDate field will be represented in this custom format in the JSON output, instead of the default serialization provided by Jackson.


Comments