Gergely Fehérvári Gergely Fehérvári - 1 month ago 12
Java Question

Jackson set default view

I am using Jackson 2.3.2, and I want to set the ObjectMapper default View






First try: http://wiki.fasterxml.com/JacksonJsonViews#Implementation



// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);

// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config

// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);


So I had:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.getSerializationConfig().setSerializationView(ResourceView.PublicView.class);


Not works JavaDoc 1.8.2 says:
setSerializationView
is deprecated, I have to use
withView()





Second try:



ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.getSerializationConfig().withView(ResourceView.PublicView.class);


Still not working. JavaDoc 2.2.0 says


public SerializationConfig withView(Class<?> view)


Description copied from class: MapperConfigBase

Method for constructing and returning a new instance with different view to use.


But I can't set the new
SerializationConfig
to the existing
ObjectMapper





How can I set default View?






UPDATE



I use Jersey and JAX-RS on the server side

Answer Source

With Jersey I had to set the View at the JacksonJsonProvider

ResourceConfig config = new ResourceConfig();
config.packages("com.example.foo");

JacksonJsonProvider jjp = new JacksonJsonProvider();
jjp.setDefaultWriteView(ResourceView.PublicView.class);
config.register(jjp);