Can I customize a Jackson ObjectMapper by adding a

2019-07-20 16:52发布

问题:

I am using a library that creates an ObjectMapper and adds some Modules of its own to this mapper. I would like the serializers in these modules to pretty print. However, my only access to configure this mapper is via a builder that lets me add my own modules. Can I use my ability to add modules to the ObjectMapper to configure it to pretty print? I'm not seeing any methods or properties of SimpleModule suggesting that I can.

回答1:

Yes, if you can register a Module with an ObjectMapper, you can manipulate the mapper. Override the setupModule() method on the Module and then use getOwner() on the Module.SetupContext that you get:

GraphSONMapper mapper = GraphSONMapper.build().addCustomModule(new SimpleModule() {                                          
    public void setupModule(com.fasterxml.jackson.databind.Module.SetupContext context) {                                    
        ObjectMapper mapper = context.getOwner();                                                                            
        mapper.enable(SerializationFeature.INDENT_OUTPUT);                                                                   
    }                                                                                                                        
}).create();                                                                                                                 
GraphSONWriter writer = graph.io().graphSONWriter().mapper(mapper).create();

The documentation for getOwner() suggests you shouldn't do this unless you have to.