Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create clone of jackson ObjectMapper Instance

Tags:

java

jackson

I'm writing a library that needs a com.fasterxml.jackson.databind.ObjectMapper instance. The user of the library should be able to provide the configuration for the ObjectMapper or the ObjectMapper instance itself. But I also add/modify some settings of the serializer without affecting the users ObjectMapper instance.

Is there any way to create a copy/clone of ObjectMapper instance?

It looks like ObjectMapper clonedInstance = new ObjectMapper(originalMapper.getFactory()) could work. But I'm not sure if there is anything what I'm missing. Will the ObjectMapper behave exactly as the original one?

Currently this is my code:

public MyLibraryClass {
    private ObjectMapper internalMapper;

    public MyLibraryClass(ObjectMapper mapper) {
        if (mapper == null) {
            internalMapper = new ObjectMapper();
        } else {
            internalMapper = new ObjectMapper(mapper.getFactory());
        }
    }
}
like image 480
Raman Avatar asked Apr 20 '26 15:04

Raman


1 Answers

You can use ObjectMapper#copy():

copy

public ObjectMapper copy()

Method for creating a new ObjectMapper instance that has same initial configuration as this instance. Note that this also requires making a copy of the underlying JsonFactory instance.

Method is typically used when multiple, differently configured mappers are needed. Although configuration is shared, cached serializers and deserializers are NOT shared, which means that the new instance may be re-configured before use; meaning that it behaves the same way as if an instance was constructed from scratch.

Since: 2.1

Example:

public MyLibraryClass {
    private ObjectMapper internalMapper;
    public MyLibraryClass(ObjectMapper mapper) {
        if (mapper == null) {
            internalMapper = new ObjectMapper();
        } else {
            internalMapper = mapper.copy();
        }
    }
}

Also see this observation from the ObjectMapper class javadocs:

(...) method copy() which creates a clone of the mapper with specific configuration, and allows configuration of the copied instance before it gets used. Note that copy() operation is as expensive as constructing a new ObjectMapper instance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.

like image 99
acdcjunior Avatar answered Apr 23 '26 04:04

acdcjunior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!