Java ConfigOverrides-class And Method Code Example


Here is an example of using the ConfigOverrides class from the com.fasterxml.jackson.databind package in Java to configure custom serialization and deserialization settings for specific classes:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.deser.DeserializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

public class Example {

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

        SimpleModule module = new SimpleModule();
        module.addSerializer(Integer.class, new ToStringSerializer());
        mapper.registerModule(module);

        ConfigOverrides configOverrides = new ConfigOverrides();
        configOverrides.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        configOverrides.setDeserializationFeature(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        mapper.setConfig(configOverrides);

        ExampleObject obj = new ExampleObject(1, "example");
        String json = mapper.writeValueAsString(obj);
        System.out.println(json);

        json = "{\"id\":1,\"name\":\"example\",\"extra_field\":\"extra\"}";
        ExampleObject deserializedObj = mapper.readValue(json, ExampleObject.class);
        System.out.println(deserializedObj);
    }
}

class ExampleObject {

    private Integer id;
    private String name;

    public ExampleObject(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "ExampleObject{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
}

In this example, a new ObjectMapper is created and configured with a custom serializer for Integer class, which will use the ToStringSerializer to serialize the Integer object.

Then, a new ConfigOverrides object is created and configured to include only non-null values during serialization and to fail on unknown properties during deserialization.

Finally, the ObjectMapper is configured with the ConfigOverrides object, and an ExampleObject is serialized and deserialized, and the output is printed to the console.

As you can see, the ConfigOverrides class allows you to configure a set of custom serialization and deserialization settings that can be applied to specific classes, instead of applying them globally to all classes.