gpt4 book ai didi

java - jackson JsonView 未被应用

转载 作者:行者123 更新时间:2023-11-30 11:23:41 24 4
gpt4 key购买 nike

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 上设置 View ,我希望此配置应用于使用此 ObjectMapper 映射的所有对象。

如何使 ObjectMapper 始终应用 JsonView 而无需调用 writerWithView,以便我可以将此 ObjectMapper 提供给 Spring MVC?

最佳答案

事实证明,如果您真正阅读了文档,您会发现您不能仅通过调用 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来设置 View 。这些方法将构造一个新的 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);
}
}

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

关于java - jackson JsonView 未被应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21048020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com