杰克逊设置默认视图

时间:2014-04-05 01:47:05

标签: java json serialization jackson

我正在使用Jackson 2.3.2,我想设置ObjectMapper默认的View


首先尝试: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);

所以我有:

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

不起作用JavaDoc 1.8.2 says: setSerializationView 已弃用,我必须使用withView()


第二次尝试:

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

仍然无法正常工作。 JavaDoc 2.2.0 says

  

public SerializationConfig withView(Class<?> view)

     

从类复制的描述:MapperConfigBase

     

使用不同视图构建和返回新实例的方法。

但我无法将新的SerializationConfig设置为现有的ObjectMapper


如何设置默认视图?


更新

我在服务器端使用Jersey和JAX-RS

3 个答案:

答案 0 :(得分:6)

应该这样做:

mapper.setConfig(mapper.getSerializationConfig().withView(ResourceView.PublicView.class));

答案 1 :(得分:0)

使用Jersey我必须在JacksonJsonProvider

处设置视图
ResourceConfig config = new ResourceConfig();
config.packages("com.example.foo");

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

答案 2 :(得分:0)

我使用Jackson 1.9.13,这对我有用:

mapper.setSerializationConfig(mapper.getSerializationConfig().withView(ResourceView.PublicView.class));