Reputation: 464
I have a problem in my webservice controller, due to jackson's serialisation of a third party object.
java.lang.IllegalArgumentException: Conflicting setter definitions for property "X": ThirdPartyClass#setX(1 params) vs ThirdPartyClass#setX(1 params)
I've read that you can solve it thanks to MixIn annotation.
In my controller i'm giving a list, i'd like to know if there is a way to automatically define somewhere the use of the MixInAnnotation ?
If i had to do return a String instead of objects, i'd do something like that:
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(xxx);
return mapper.writeValueAsString(myObject);
Nevertheless, my controller is giving List:
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<MyObject> getMyObjects
and several times returning MyObject in other methods, and so i'd like to declare only one time the use of the MixInAnnotation for jackson serialisation ?
Thank you, RoD
Upvotes: 1
Views: 3003
Reputation: 19231
I suggest that you use the "Spring Way" of doing this by following the steps provided in the Spring Docs.
If you want to replace the default
ObjectMapper
completely, define a@Bean
of that type and mark it as@Primary
.Defining a
@Bean
of typeJackson2ObjectMapperBuilder
will allow you to customize both defaultObjectMapper
andXmlMapper
(used inMappingJackson2HttpMessageConverter
andMappingJackson2XmlHttpMessageConverter
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 typeObjectMapper
, providing a global mechanism for contributing custom modules when you add new features to your application.
Basically this means that if you simply register a Module
as a bean with the provided mixin-settings you should be all set and there will be no need to define your own ObjectMapper
or to alter the HttpMessageConverter
s.
Upvotes: 1
Reputation: 464
So, in order to do this, i customised the Jackson JSON mapper in Spring Web MVC.
Custom mapper:
@Component
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
this.addMixInAnnotations(Target.class, SourceMixIn.class);
}
}
Register the new mapper at start up of spring context:
@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);
}
}
}
}
Thanks to that, i didn't modify my WebService Controller.
Upvotes: 0