JSON JSON switch from camel to underline (snake case)

I recently switched to jersey 2 ,. I looked through the documentation / web and found out how to convert the response class to a custom class using .readEntity(ClassName.class);

But I'm stuck with using the CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES naming CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES .

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

Any help would be appreciated.

In jersey1, I did this:

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

I cannot achieve the same thing after Jersey 2: It gives a compile-time error when I, as in the code above:

I also tried:

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

but it does not create myResponse object, because the answer I get has the answer Snake_case, but my POJO has camel case fields.

+5
source share
1 answer

This is what you need to configure using Jackson ObjectMapper . You can do this in 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 also need this support on the server, you will also need to register it on the server.

+5
source

Source: https://habr.com/ru/post/1247178/


All Articles