0

I'm using Jersey with Spring for a REST API and I wrote a provider to modify JSON serialization. The problem is that when I use the @Component annotation, the provider's callback method is called for other servlets. When I remove the @Component annotation, it doesn't get called at all.
Here is the provider:

@Component
@Provider

public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

public ObjectMapperProvider() {
}

@Override
public ObjectMapper getContext(Class<?> type) {
     ObjectMapper objectMapper = new ObjectMapper();
     SimpleModule module = new SimpleModule("SimpleModule", new org.codehaus.jackson.Version(1, 0, 0, null));
     module.addSerializer(BigInteger.class, new ToStringSerializer());
     objectMapper.registerModule(module);
     return objectMapper;   
}
}

I tried to use the Jersey configuration in the web.xml, but that didn't help either.
Any ideas?

1 Answer 1

0

Apparently, that wasn't my problem. The provider was called for the right servlet.
My application didn't work because I had an XmlAdapter for Map, and with my ObjectMapperProvider, the json response was different.
Here is my updated ObjectMapperProvider class:

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {


     @Context
     UriInfo uriInfo;

    public ObjectMapperProvider() {
    }


    @Override
    public ObjectMapper getContext(Class<?> type) {
         ObjectMapper objectMapper = new ObjectMapper();
         SimpleModule module = new SimpleModule("SimpleModule", new org.codehaus.jackson.Version(1, 0, 0, null));
         module.addSerializer(BigInteger.class, new ToStringSerializer());
         objectMapper = objectMapper.configure(Feature.WRAP_ROOT_VALUE, false).configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, false)
                 .configure(Feature.WRAP_EXCEPTIONS, true).configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true).configure(Feature.WRITE_EMPTY_JSON_ARRAYS, false);
         final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
         objectMapper.getDeserializationConfig().setAnnotationIntrospector(introspector); // using a deprecated API that works. Non-deprecated API doesn't work...
         objectMapper.getSerializationConfig().setAnnotationIntrospector(introspector);
         objectMapper.registerModule(module);
         return objectMapper;   
    }

} 

Once I configured my Object wrapper to use JAXB annotations, everything worked as expected. I got the idea on how to do that from the following post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.