Java JsonUnwrapped-class And Method Code Example


Here is an example of how to use the JsonUnwrapped annotation from the Apache Commons IO library to serialize a nested object without wrapping it in an additional JSON object:

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

public class Example {

    public static class Address {
        private String street;
        private String city;
        private String state;
        // getters and setters
    }

    public static class Person {
        private String name;
        @JsonUnwrapped
        private Address address;
        // getters and setters
    }

    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("John Doe");
        Address address = new Address();
        address.setStreet("123 Main St");
        address.setCity("Anytown");
        address.setState("CA");
        person.setAddress(address);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(person);
        System.out.println(json);
    }
}

This will output:

{"name":"John Doe","street":"123 Main St","city":"Anytown","state":"CA"}

As you can see, the fields of the Address object are included directly in the JSON output for the Person object, without being wrapped in a separate JSON object.

Note: This is using the Jackson JSON library to serialize the POJO to JSON. You need to have the jackson-databind jar in your classpath for this to work.