杰克逊设置默认视图 [英] Jackson set default view
问题描述
// 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 说: setSerializationView
已弃用,我必须使用 withView()
Not works JavaDoc 1.8.2 says: setSerializationView
is deprecated, I have to use 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 表示
Still not working. JavaDoc 2.2.0 says
public SerializationConfig withView (类<?>视图)
从类复制的说明:MapperConfigBase
Description copied from class: MapperConfigBase
构建和返回具有不同视图的新实例的方法。
Method for constructing and returning a new instance with different view to use.
但我不能将新的 SerializationConfig
设置为现有的 ObjectMapper
But I can't set the new SerializationConfig
to the existing ObjectMapper
我在服务器端使用Jersey和JAX-RS
I use Jersey and JAX-RS on the server side
推荐答案
使用Jersey我必须将视图设置为 JacksonJsonProvider
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);
这篇关于杰克逊设置默认视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!