Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure java jackson not to throw NPE exception on empty beans?

Tags:

java

rest

jackson

I am trying to see how can I convince jackson to do nothing instead of throwing exceptions on empty beans. You can see the full code here.

org.codehaus.jackson.map.JsonMappingException: No serializer found for class java.lang.Exception and no properties discovered to create BeanSerializer (to avoid
exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
    at org.codehaus.jackson.map.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:52)
    at org.codehaus.jackson.map.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:25)
    at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
like image 244
sorin Avatar asked Feb 14 '23 03:02

sorin


1 Answers

You need to turn off the serialization feature FAIL_ON_EMPTY_BEANS. You can do that by setting the following on your ObjectMapper:

import org.codehaus.jackson.map.SerializationConfig.Feature;

ObjectMapper mapper = new ObjectMapper();
mapper.disable(Feature.FAIL_ON_EMPTY_BEANS);

In order to configure custom ObjectMapper settings in JAX-RS you need to create a Provider or a ContextResolver. You can use either one or the other. These allow your JAX-RS framework to lookup what ObjectMapper you would like it to use instead of using the default configuration. These will get scanned at startup of your application and registered with your framework.

Here is an example of a Provider:

@Named
@Provider
public class MyJacksonJsonProvider extends JacksonJsonProvider
{
    @Override
    public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, 
            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) 
            throws IOException 
    {
        ObjectMapper mapper = locateMapper(type, mediaType);

        mapper.disable(Feature.FAIL_ON_EMPTY_BEANS);

        super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
    }
}

Here is an example of how to do the same thing as the Provider using a ContextResolver:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class ObjectMapperResolver implements ContextResolver<ObjectMapper> 
{
    private final ObjectMapper mapper;

    public ObjectMapperResolver() 
    {
        mapper = new ObjectMapper();
        mapper.disable(Feature.FAIL_ON_EMPTY_BEANS);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) 
    {
        return mapper;
    }
}
like image 142
gregwhitaker Avatar answered Feb 17 '23 14:02

gregwhitaker