如何通过“jackson2ObjectMapperBuilder”在Jackson中启用“全局默认输入”

时间:2018-03-12 14:36:43

标签: java spring jackson

我在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(??)是否有帮助。

1 个答案:

答案 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);