我试图看看我怎么能说服杰克逊什么也不做,而不是在空豆上抛出异常。您可以看到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)
答案 0 :(得分:8)
您需要关闭序列化功能FAIL_ON_EMPTY_BEANS
。您可以通过在ObjectMapper上设置以下内容来实现:
import org.codehaus.jackson.map.SerializationConfig.Feature;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(Feature.FAIL_ON_EMPTY_BEANS);
要在JAX-RS中配置自定义ObjectMapper设置,您需要创建Provider
或ContextResolver
。您可以使用其中一个。这些允许您的JAX-RS框架查找您希望使用的ObjectMapper,而不是使用默认配置。这些将在您的应用程序启动时进行扫描,并在您的框架中注册。
以下是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);
}
}
以下是如何使用Provider
与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;
}
}