Here are my thoughts on your options. First of all
So, for every other answer, should I configure ObjectMapper differently?
If you want to use both versions of json in different places like
public Response getObject() // returns {"cinter" : {"state" : 1,"checks" : 10}} public Response getShortNamesObject() // returns {"cin" : {"st" : 1,"cs" : 10}}
Than yep, you need to use multiple ObjectMappers .
But if you just want to use one view all over the world, then you can probably set up Jackson once with a custom mixin for your classes. In any case, here's how you can do both: And let's look at a simple case using just one version of json
public class TestBean { private String name; private int id; //getters and setters } public interface TestBeanMixin { @JsonProperty("short_field_name") String getName(); @JsonProperty("short_field_id") int getId(); } @Provider @Priority(1) public class MixInJacksonJsonProvider extends JacksonJaxbJsonProvider { private static final ObjectMapper mapper = createMapper(); public MixInJacksonJsonProvider() { setMapper(mapper); } private static ObjectMapper createMapper() { final ObjectMapper result = new ObjectMapper(); result.addMixIn(TestBean.class, TestBeanMixin.class); return result; } }
This code will generate short names for POJO fields everywhere. and to implement different behavior for different requests, we need to add a new user annotation, for example:
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface MixIn {}
The controller will look like this:
@Path("test") public class MyResource { @GET @MixIn // <== Here is important part @Produces(MediaType.APPLICATION_JSON ) public Response getShortName() { return Response.ok(demoObj()).build(); } @POST @Produces(MediaType.APPLICATION_JSON ) public Response postLongName() { return Response.ok(demoObj()).build(); } }
And our MixInJacksonJsonProvider will have 2 more @Override :
//.. same as before @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return super.isReadable(type, genericType, annotations, mediaType) && hasMixInAnnotation(annotations); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return super.isWriteable(type, genericType, annotations, mediaType) && hasMixInAnnotation(annotations); } public static boolean hasMixInAnnotation(Annotation[] annotations){ for(Annotation annotation: annotations){ if (annotation instanceof MixIn){ return true; } } return false; } }
Here is the demo code for the game: https://github.com/varren/jersey2-jacksonsetup/tree/master/src/main/java/ru/varren