Can I customize a Jackson ObjectMapper by adding a

2019-07-20 16:30发布

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条回答
看我几分像从前
2楼-- · 2019-07-20 17:06

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.

查看更多
登录 后发表回答