在Spring Boot应用程序中配置Jackson Mixin [英] Configuring Jackson mixin in Spring Boot application

查看:193
本文介绍了在Spring Boot应用程序中配置Jackson Mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的班级创建了一个mixin. mixin本身可以很好地工作,这不是大多数人在混合faterxml/codehaus注释的地方的问题. 我在单元测试中对其进行了测试,并使用addMixIn方法手动"创建了ObjectMapper-它工作得很好.

I created a mixin for my class. The mixin itself works fine, it's not the issue that most people have where they mix faterxml/codehaus annotations. I tested it in a unit test, creating the ObjectMapper "by hand" while using the addMixIn method - it worked just fine.

我想使用该mixin修改从我的REST端点返回的响应json. 我试图以多种不同方式自定义Spring Boot的ObjectMapper:

I want to use that mixin to modify the response jsons returned from my REST endpoints. I've tried to customize Spring Boot's ObjectMapper in many different ways:

BuilderCustomizer:

BuilderCustomizer:

@Bean
public Jackson2ObjectMapperBuilderCustomizer addMixin(){
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.mixIn(MyClass.class, MyClassMixin.class);                
        }
    };
}

Builder:

@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder().mixIn(MyClass.class, MyClassMixin.class);
}

转换器:

@Bean
public MappingJackson2HttpMessageConverter configureJackson(){
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(MyClass.class, MyClassMixin.class);
    converter.setObjectMapper(mapper);
    return converter;
}

ObjectMapper:

ObjectMapper:

@Autowired(required = true)
public void configureJackon(ObjectMapper jsonMapper){
    jsonMapper.addMixIn(MyClass.class, MyClassMixin.class);
}

这些工作都没有.

推荐答案

这可能取决于Spring Boot版本,但根据

This might depend on Spring Boot version but as per Customize the Jackson ObjectMapper defining a new Jackson2ObjectMapperBuilderCustomizer bean is sufficient

可以通过一个或多个Jackson2ObjectMapperBuilderCustomizer Bean自定义上下文的Jackson2ObjectMapperBuilder.可以对此类定制器bean进行排序(Boot自己的定制器的顺序为0),从而可以在Boot定制之前和之后应用其他定制.

The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

这篇关于在Spring Boot应用程序中配置Jackson Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆