使用 ContextResolver 在运行时注册 ObjectMapper



我们使用JAX-RS(泽西实现(来调用外部系统。 在创建 JAX-RS 客户端时,我正在注册以下上下文解析器以使用自定义 ObjectMapper:

public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper>
{
@Override
public ObjectMapper getContext(Class<?> type) 
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper;
}   
}

但我不想在JacksonObjectMapperProvider中定义ObjectMapper。我希望 JacksonObjectMapperProvider 能够在运行时从某个地方检索它,或者让某人在 JacksonObjectMapperProvider 上设置 ObjectMapper。

我不能做像下面这样的事情,因为ObjectMapper是在创建jax-rs客户端的某个实例上定义的。在这里我没有对该实例的引用:

public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper>
{
@Override
public ObjectMapper getContext(Class<?> type) 
{
return someService.getObjectMapper();
}   
}

有没有其他方法可以做到这一点? 在客户端上注册时,有没有办法将数据传递给JacksonObjectMapperProvider?

解决方案比我想象的要容易,而不是注册类:

ClientConfig clConfig = new ClientConfig();
client.register(JacksonObjectMapperProvider.class);

就像我所做的那样,您可以注册类的实例,并在创建实例时传递您想要的任何内容:

ClientConfig clConfig = new ClientConfig();
client.register(new JacksonObjectMapperProvider(objectMapper));

更新的提供程序:

public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper>
{
private ObjectMapper mapper;
public JacksonObjectMapperProvider(ObjectMapper mapper)
{
this.mapper = mapper;
}
@Override
public ObjectMapper getContext(Class<?> type) 
{
return mapper;
}   
}

相关内容

  • 没有找到相关文章

最新更新