Jackson JsonView未被应用

时间:2014-01-10 15:24:03

标签: java jackson

Jackson 2.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?

1 个答案:

答案 0 :(得分:1)

如果你真正阅读了你发现的文档,你不能通过调用getSerializationConfig并在其上调用setter来改变序列化配置。

/**
 * Method that returns the shared default {@link SerializationConfig}
 * object that defines configuration settings for serialization.
 *<p>
 * 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<HttpMessageConverter<?>> 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);
    }
  }

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