Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Jackson serializer of resteasy client

Is it possible to register a custom Jackson JSON serializer for the resteasy client?

I've tried to do something like:

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

But it didn't work. Any ideas?

like image 666
Chico Sokol Avatar asked Dec 09 '22 04:12

Chico Sokol


2 Answers

You can only register JAX-RS components like Providers or Features. You need to register an Provider which carries an ObjectMapper which carries an Module with your serializer registered.

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();

Note that this example is using the classes from org.codehaus.jackson. The API from com.fasterxml.jackson looks slightly different.

like image 189
lefloh Avatar answered Dec 10 '22 17:12

lefloh


Alternative solution

Looking into the source code, ResteasyJackson2Provider has the following annotations

    @Provider
    @Consumes({"application/*+json", "text/json"})
    @Produces({"application/*+json", "text/json"})

so I have preferred to create a provider class with specific annotations to be sure it will be chosen first:

    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...
        }
  }
like image 34
felix at housecat Avatar answered Dec 10 '22 16:12

felix at housecat