通过构造一个新的映射器,我在Spring Boot配置中定制了对Jackson对象映射器中集合的处理,如下所示
@Configuration
public class Config {
@Autowired(required = true)
public void objectMapper(ObjectMapper mapper) {
mapper.configOverride(Collection.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));
mapper.configOverride(List.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));
mapper.configOverride(Map.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));
}虽然这是可行的,但我知道更优雅的方法是使用Jackson2ObjectMapperBuilderCustomizer:
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizeJackson2ObjectMapper() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder
.indentOutput(true)
.someOtherMethod(...)
}
};
}我如何通过Jackson2ObjectMapperBuilder实现上面的ObjectMapper集合调整?
发布于 2019-01-03 06:33:44
您可以使用本地定义的简单Module,就像在this other use case中一样。SetupContext也有一个configOverride()方法,就像ObjectMapper本身一样。
发布于 2019-01-03 02:48:49
不知道?我有兴趣做同样的事情,只是补充一下:
mapper.configOverride(Map.Entry.class).setFormat(forShape(Shape.OBJECT));因为@JsonFormat(shape = JsonFormat.Shape.OBJECT)不能很好地工作( https://github.com/FasterXML/jackson-databind/issues/1419 ),而且在Jackson 2.5之后,它是唯一的解决方案(但需要2.9.x)来恢复以前的行为,而不需要编写自定义的序列化程序。
https://stackoverflow.com/questions/41141573
复制相似问题