Jersey 实际上并没有显式配置 ObjectMapper 实例,而是委托给JacksonJsonProvider
,而后者又使用默认映射器实例。您可以跟踪JacksonProviderProxy 代码以查看它是如何工作的。您可以通过定义上下文解析器来创建和自定义要在整个应用程序中使用的共享映射器:
@Provider
public class ObjectMapperContextResolver implements
ContextResolver<ObjectMapper> {
private ObjectMapper mapper = null;
public ObjectMapperContextResolver() {
super();
// Illustrate configuration of the mapper instance
mapper = new ObjectMapper().configure(
SerializationConfig.Feature.WRAP_ROOT_VALUE, true).configure(
DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
Jackson 提供程序将从该解析器中检索其映射器实例,您可以在代码中执行相同操作,如下所示:
public class MyResource {
@Context
private ContextResolver<ObjectMapper> mapperResolver;
public void someResourceMethod() {
final ObjectMapper mapper = mapperResolver.getContext(Object.class);
}
}