Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 381
Gergely Fehérvári Avatar asked Apr 05 '14 01:04

Gergely Fehérvári


1 Answers

It should work by doing:

mapper.setConfig(mapper.getSerializationConfig().withView(ResourceView.PublicView.class));
like image 105
john16384 Avatar answered Sep 20 '22 00:09

john16384