定制杰克逊序列化的resteasy客户端

时间:2015-03-12 14:38:28

标签: java java-ee jax-rs resteasy

是否可以为resteasy客户端注册自定义Jackson JSON序列化程序?

我试图做类似的事情:

ResteasyClient client = new ResteasyClientBuilder()
            .register(new CustomSerializer())
            .build();

但它没有用。有什么想法吗?

2 个答案:

答案 0 :(得分:12)

您只能注册ProvidersFeatures等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...
        }
  }