Java Jackson @JsonRootName Example

1. Introduction

Jackson offers a bunch of annotations to cater to various customization needs during serialization and deserialization. One such annotation is @JsonRootName. It is used to customize the name of the root element when wrapping the main object. Essentially, when you want to wrap your object inside a single JSON root name during serialization, @JsonRootName will come in handy.

2. Example Steps

1. Create a User class annotated with @JsonRootName to specify a custom root name.

2. Enable SerializationFeature.WRAP_ROOT_VALUE in the ObjectMapper to ensure the root name is included during serialization.

3. Serialize an instance of the User class and observe the output.

3. Java Jackson @JsonRootName Example

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonJsonRootNameExample {

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

        // Enable the WRAP_ROOT_VALUE feature
        mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);

        // Create a User instance
        User user = new User(1, "John Doe");

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

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

    @JsonRootName(value = "userDetail")
    static class User {
        private int id;
        private String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        // Standard getters and setters omitted for brevity
    }
}

Output:

{"userDetail":{"id":1,"name":"John Doe"}}

4. Step By Step Explanation

The @JsonRootName annotation is used to specify a custom root name for the serialized JSON output. However, this annotation alone isn't sufficient. To actually wrap the serialized object with the root name, we need to enable the SerializationFeature.WRAP_ROOT_VALUE feature in our ObjectMapper.

In our example, the User class is annotated with @JsonRootName(value = "userDetail"). This means, when an instance of the User class is serialized, it will be wrapped inside a "userDetail" root element. The result of serializing a user with ID "1" and name "John Doe" gives the JSON {"userDetail":{"id":1,"name":"John Doe"}}.


Comments