是否可以为resteasy客户端注册自定义Jackson JSON序列化程序?
我试图做类似的事情:
ResteasyClient client = new ResteasyClientBuilder()
.register(new CustomSerializer())
.build();
但它没有用。有什么想法吗?
答案 0 :(得分:12)
您只能注册Providers或Features等JAX-RS组件。 您需要注册一个提供程序,该提供程序带有一个ObjectMapper,它带有一个带有序列化程序的模块。
ResteasyJacksonProvider resteasyJacksonProvider = new ResteasyJacksonProvider();
ObjectMapper mapper = new ObjectMapper();
SimpleModule myModule = new SimpleModule("myModule", new Version(1, 0, 0, null));
myModule.addSerializer(Custom.class, new CustomSerializer());
mapper.registerModule(myModule);
resteasyJacksonProvider.setMapper(mapper);
ResteasyClient client = new ResteasyClientBuilder().register(resteasyJacksonProvider).build();
请注意,此示例使用org.codehaus.jackson
中的类。来自com.fasterxml.jackson
的API看起来略有不同。
答案 1 :(得分:0)
替代解决方案
查看源代码,ResteasyJackson2Provider
具有以下注释
@Provider
@Consumes({"application/*+json", "text/json"})
@Produces({"application/*+json", "text/json"})
所以我更喜欢创建一个带有特定注释的提供者类,以确保它将首先被选中:
public class RestEasyClientJackson {
private ObjectMapper mapper;
private JacksonJsonProvider provider;
private Client client;
@Before
public void setUp() throws Exception {
mapper = new ObjectMapper();
mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
provider = new MyProvider(mapper);
client = ClientBuilder.newBuilder().register(provider).build();
}
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
class MyProvider extends JacksonJsonProvider {
MyProvider(ObjectMapper mapper) {
super(mapper);
}
@Test
public void myTest() throws Exception {
// some test code...
}
}