// 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
答案 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));