Search code examples
javajsonjacksonjersey-2.0camelcasing

Jersey JSON switching from camel case to underscores (snake case)


I recently switched to jersey 2 ,. I went through the documentation/web and got to know how to convert response class to custom class using .readEntity(ClassName.class);

But I am stuck at using CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES naming strategy.

The current conversion fails as the response fields are with "_" and my POJO has Snake case .

Any help will be appreciated.

In jersey1 , I have been doing this :

MyResponse myResponse = client  
        .resource(url)
        .type(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .post(RequestClass.class, request);

the same I am not able to achieve post jersey 2 : It gives compile time error when I as in above code :

I also tried :

MyResponse myResponse = client
        .target(getUrl())
        .request()
        .post(Entity.entity(request, MediaType.APPLICATION_JSON))
        .readEntity(MyResponse.class);

but it's not creating myResponse object , cause the response I get has Snake_case response but my POJO has camel case fields.


Solution

  • This is something that needs to be configured with the Jackson ObjectMapper. You can do this in a ContextResolver. Basically, you need something like

    @Provider
    public class MapperProvider implements ContextResolver<ObjectMapper> {
        final ObjectMapper mapper;
    
        public MapperProvider() {
            mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(
                    PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        }
    
        @Override
        public ObjectMapper getContext(Class<?> cls) {
            return mapper;
        }
    }
    

    Then register with your client

    client.register(MapperProvider.class);
    

    If you need this support on the server also, then you will need to register it on the server too.