Java Jackson @JsonUnwrapped Example

1. Introduction

The Jackson Library provides an annotation called @JsonUnwrapped, which can be utilized to flatten the properties of an embedded object. This means that instead of serializing an embedded object with its own set of curly braces {}, its properties are instead merged into the parent object. This can help simplify and flatten JSON structures when required.

2. Example Steps

1. Create a Name class with properties: firstName and lastName.

2. Create a User class that contains a Name object and a field for age.

3. Annotate the Name property in the User class with @JsonUnwrapped to flatten its fields during serialization.

4. Create an instance of the User class.

5. Serialize the User instance into a JSON string.

6. Print the JSON string to see the flattened structure.

3. Java Jackson @JsonUnwrapped Example

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

public class User {

    @JsonUnwrapped
    private Name name;

    private int age;

    public User(Name name, int age) {
        this.name = name;
        this.age = age;
    }

    public static class Name {
        private String firstName;
        private String lastName;

        public Name(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    }

    public static void main(String[] args) throws Exception {
        // Create an instance of User
        User user = new User(new Name("John", "Doe"), 30);

        // Create an ObjectMapper instance
        ObjectMapper mapper = new ObjectMapper();

        // Serialize the User instance into a JSON string
        String jsonString = mapper.writeValueAsString(user);

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

Output:

{"firstName":"John","lastName":"Doe","age":30}

4. Step By Step Explanation

In the above code, we've created a User class containing an embedded Name object. By default, when serializing an object of User, the Name would be serialized as a nested JSON object. However, by using the @JsonUnwrapped annotation, the properties of the Name object (firstName and lastName) are "unwrapped" or "flattened" into the parent User object, producing a simpler JSON structure as seen in the output.


Comments