问题
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());
}
}
}
回答1:
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 underlyingJsonFactory
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 thatcopy()
operation is as expensive as constructing a newObjectMapper
instance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.
回答2:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class Hello {
static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) {
ObjectNode root = mapper.createObjectNode();
root.put("ABC" , 123);
ObjectNode human = root.deepCopy();
root.put("DEF", 123);
System.out.println(root);
System.out.println(human);
}
}
This returned the following respectively.
{"ABC":123, "DEF":123}
{"ABC":123"}
来源:https://stackoverflow.com/questions/58558071/create-clone-of-jackson-objectmapper-instance