杰克逊的 属性 与 setter 冲突

Conflicting setter for property in jackson

由于 jackson 对第三方对象的序列化,我的网络服务控制器出现问题。

java.lang.IllegalArgumentException: Conflicting setter definitions for property "X": ThirdPartyClass#setX(1 params) vs ThirdPartyClass#setX(1 params)

我读到你可以通过 MixIn 注释解决它。

在我的控制器中,我给出了一个列表,我想知道是否有一种方法可以自动定义某处使用 MixInAnnotation 的方法?

如果我必须做 return 字符串而不是对象,我会做这样的事情:

ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(xxx);
return mapper.writeValueAsString(myObject);

尽管如此,我的控制器给出了列表:

@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<MyObject> getMyObjects

并在其他方法中多次 returning MyObject,所以我只想声明一次使用 MixInAnnotation 进行 jackson 序列化?

谢谢, RoD

因此,为了做到这一点,我在 Spring Web MVC 中自定义了 Jackson JSON 映射器。

自定义映射器:

@Component
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        this.addMixInAnnotations(Target.class, SourceMixIn.class);
    }
}

在 spring 上下文启动时注册新映射器:

@Component
public class JacksonInit {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Autowired
    private CustomObjectMapper objectMapper;

    @PostConstruct
    public void init() {
        List<HttpMessageConverter<?>> messageConverters = requestMappingHandlerAdapter.getMessageConverters();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter m = (MappingJackson2HttpMessageConverter) messageConverter;
                m.setObjectMapper(objectMapper);
            }
        }
    }
}

多亏了那个,我没有修改我的 WebService 控制器。

我建议您按照 Spring Docs 中提供的步骤使用“Spring 方式”来执行此操作。

If you want to replace the default ObjectMapper completely, define a @Bean of that type and mark it as @Primary.

Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).

Another way to customize Jackson is to add beans of type com.fasterxml.jackson.databind.Module to your context. They will be registered with every bean of type ObjectMapper, providing a global mechanism for contributing custom modules when you add new features to your application.

基本上这意味着,如果您简单地将 Module 注册为具有提供的 mixin-settings 的 bean,您应该已经准备就绪,并且无需定义您自己的 ObjectMapper 或改变 HttpMessageConverters.