2
votes

I have a client application that I am using to consume some API and update it. I am using Jersey 2.25.1 with Jersey Jackson and no custom connectors, just the basic setup.

I have a POJO that I am serializing using Jackson and Jersey, but I need this POJO to be serialized in two ways, first is to include all null values while serializing them, and second is to ignore and remove null fields.

This is how the API works so the API cannot be changed (it's not my API), so I am asking can I update the Jersey Jackson Mapper at runtime?

What I am looking for is something like:

 Client client = ClientBuilder.newBuilder()
            .register(JacksonFeature.class)
            .build();
 client.getJacksonObjectMapper().setSerializationInclusion(Include.NON_NULL); 
1

1 Answers

1
votes

You can use a ContextResolver, and configure the ObjectMapper there. The Jackson provider will call the context resolver to get the ObjectMapper

class JacksonResolver implements ContextResolver<ObjectMapper> {
    private final ObjectMapper mapper = new ObjectMapper();

    public JacksonResolver() {
        // configure mapper
    }

    @Override
    public ObjectMapper resolve(Class<?> cls) {
        return this.mapper;
    }
}

Client client = ClientBuilder.newBuilder()
        .register(JacksonFeature.class)
        .register(new JacksonResolver())
        .build();