我在Spring应用程序中使用Jackson。我正在通过bean配置Jackson:
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer configureJackson() {
return jackson2ObjectMapperBuilder -> {
jackson2ObjectMapperBuilder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE);
jackson2ObjectMapperBuilder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
};
}
}
现在我想配置“全局默认输入” - 我希望所有序列化对象都包含类型信息。
我没有找到任何合适的“功能”,我不知道jackson2ObjectMapperBuilder.defaultTyping(??)
是否有帮助。
答案 0 :(得分:4)
你可以这样做。
@Bean
public Jackson2ObjectMapperBuilderCustomizer configureJackson() {
return jackson2ObjectMapperBuilder -> {
TypeResolverBuilder<?> typeResolver = new ObjectMapper.DefaultTypeResolverBuilder(OBJECT_AND_NON_CONCRETE);
typeResolver = typeResolver.init(JsonTypeInfo.Id.CLASS, null);
typeResolver = typeResolver.inclusion(JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2ObjectMapperBuilder.defaultTyping(typeResolver);
};
}
这相当于
objectMapper.enableDefaultTyping(OBJECT_AND_NON_CONCRETE, WRAPPER_ARRAY);