简体   繁体   中英

How to obtain Jackson Object Mapper in Spring Rest mvc 5?

I want to obtain the ObjectMapper (or mappers) that Spring 5 creates, configures and uses to serialize and deserialize data exchanges on my Rest resources (ie to call readerForUpdating() on it or to provide further configuration such as adding mixins).

I've tried the solutions proposed in this question but none worked: I'm not using Spring Boot and neither of ObjectMapper or MappingJackson2HttpMessageConverter can be @Autowired .

In particular, I've tried reconfiguring the ObjectMapper from the MappingJackson2HttpMessageConverter:

@EnableWebMvc
@Configuration
@EnableSwagger2
@ComponentScan(basePackages=...)
public class WebappConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // ...
        for(HttpMessageConverter<?> c : converters) {

            if(c instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper o = ((MappingJackson2HttpMessageConverter) c).getObjectMapper();

                //o.configure(SerializationFeature.INDENT_OUTPUT, true);
                o.addMixIn(WorkStamp.class, WorkStampApi.class);
            }
        }
        //...
    }
}

But that's not working either, as that mixin removes a field from the serialized object but the produced JSON still has that field.

Here's my solution: basically, during webapp initialization I obtain a reference to the mapper inside the relevant Spring message converter, I then store that reference to be retrieved later as a bean from the context.

This is the Spring webapp configuration class:

@EnableWebMvc
@Configuration
@EnableSwagger2
@ComponentScan(basePackages= { "..." })
@PropertySource("...")
public class WebappConfig implements WebMvcConfigurer {

    private ObjectMapper jacksonMapper;

    @Bean(name="jacksonMapper",autowire=Autowire.BY_NAME)
    public ObjectMapper getMapper() {
        return jacksonMapper;
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        Iterator<HttpMessageConverter<?>> it = converters.iterator();

        while(it.hasNext()) {
            HttpMessageConverter<?> conv = it.next();

            if(conv instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) conv;
                jacksonMapper = jacksonConverter.getObjectMapper();
            }
        }
    }

}

And here's an example of that Object Mapper usage:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(path="...")
public class Controller {

    @Autowired
    private ApplicationContext ctx;

    @PostMapping(path= { "..." })
    public ApiResponse<?> post() {

        try {
            // ...

            ObjectMapper om = (ObjectMapper) ctx.getBean("jacksonMapper");

            // ...

            return new ApiResponse<>();
        } catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM