Java UnwrappedPropertyHandler-class And Method Code Example


Here is an example of using the UnwrappedPropertyHandler class from the Jackson Databind library in Java:

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.ser.impl.UnwrappedPropertyHandler;

public class Example {
    public static class Address {
        public String street;
        public String city;
    }

    public static class User {
        public String name;

        @JsonUnwrapped
        public Address address;
    }

    public static class CustomUnwrappedPropertyHandler extends UnwrappedPropertyHandler {
        public CustomUnwrappedPropertyHandler(BeanPropertyDefinition propertyDef, AnnotatedMethod getter, AnnotatedMethod setter) {
            super(propertyDef, getter, setter);
        }

        @Override
        public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
            Address address = (Address) getter.invoke(bean);
            gen.writeStringField("street", address.street);
            gen.writeStringField("city", address.city);
        }
    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.addHandler(new CustomUnwrappedPropertyHandler());
        User user = new User();
        user.name = "John";
        user.address = new Address();
        user.address.street = "Main St";
        user.address.city = "Anytown";
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
    }
}

The output of the example above will be:

{"name":"John","street":"Main St","city":"Anytown"}

In this example, the Address properties are serialized as if they were direct properties of the User class, because of the use of the @JsonUnwrapped annotation on the address field. The custom UnwrappedPropertyHandler class is used to specify how the properties should be serialized.