Java Jackson @JsonValue Example

1. Introduction

In the case of JSON serialization and deserialization using Jackson, there are multiple annotations to customize the output. One of these annotations is @JsonValue. This annotation can be used to indicate a single method in a class that will be used to serialize the entire object's output. Instead of the default behavior of serializing all the properties of the object, the method marked with @JsonValue will determine the sole value for the serialization.

2. Example Steps

1. Create a Role class with an enumeration of roles and a description.

2. Annotate the getDescription method with @JsonValue.

3. Serialize an instance of the Role class to observe the customized output.

3. Java Jackson @JsonValue Example

import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonValueExample {

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

        // Create an instance of Role
        Role userRole = Role.USER;

        // Serialize the Role instance
        String serializedRole = mapper.writeValueAsString(userRole);

        // Print the serialized role
        System.out.println(serializedRole);
    }

    enum Role {
        USER("User has limited access"),
        ADMIN("Admin has full access");

        private String description;

        Role(String description) {
            this.description = description;
        }

        @JsonValue
        public String getDescription() {
            return description;
        }
    }
}

Output:

"User has limited access"

4. Step By Step Explanation

The @JsonValue annotation signals to Jackson that the annotated method should be used to get the serialized value for the enclosing class instance. 

In the example provided, instead of serializing the Role enumeration's name (like "USER" or "ADMIN"), Jackson serializes the output of the getDescription method due to the @JsonValue annotation. As a result, when we serialize the Role.USER instance, the output is the description of the user role, i.e., "User has limited access", rather than the default enumeration name "USER".


Comments