Jackson JsonView未被应用

jackson2.2.2

ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().withView(Views.Public.class); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); // if I try to simply configure using .without that config feature doesn't get set. // I MUST use the .configure as above, but I guess that's a different question. // .without(MapperFeature.DEFAULT_VIEW_INCLUSION); // this first one doesn't have the view applied. String result = mapper.writeValueAsString(savedD); // this second one works. result = mapper.writerWithView(Views.Public.class).writeValueAsString(savedD); 

我希望这个配置,我在SerializationConfig上设置视图,以应用于使用此ObjectMapper映射的所有对象。

如何让ObjectMapper始终应用JsonView而不必调用writerWithView这样我就可以将这个ObjectMapper赋予Spring MVC?

事实certificate,如果您确实阅读了您发现的文档,您不能通过调用getSerializationConfig并在其上调用setter来更改序列化配置。

 /** * Method that returns the shared default {@link SerializationConfig} * object that defines configuration settings for serialization. *

* Note that since instances are immutable, you can NOT change settings * by accessing an instance and calling methods: this will simply create * new instance of config object. */ SerializationConfig getSerializationConfig();

我再说一遍, 你不能通过访问实例和调用方法来更改设置:

所以你必须调用.configure方法而不是.without ,你不能通过调用.withView来设置视图。 这些方法将构造一个SerializationConfig的新实例,但是没有办法让你的新SerializationConfig重新进入ObjectMapper。

为了解决这个问题并将我的ObjectMapper连接到Spring MVC处理@ResponseBody时,我实现了以下内容:

  @Configuration class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper() { private static final long serialVersionUID = 1L; @Override protected DefaultSerializerProvider _serializerProvider(SerializationConfig config) { // replace the configuration with my modified configuration. // calling "withView" should keep previous config and just add my changes. return super._serializerProvider(config.withView(Views.Public.class)); } }; mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); converter.setObjectMapper(mapper); converters.add(converter); } } 

有了这一切,一切都对我有用。