Can I customize a Jackson ObjectMapper by adding a module?

我们两清 提交于 2019-12-12 17:18:47

问题


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.



来源:https://stackoverflow.com/questions/28255878/can-i-customize-a-jackson-objectmapper-by-adding-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!