jackson2ObjectMapperBuilder

jackson2ObjectMapperBuilder

我在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(??)是否可以提供帮助。

最佳答案

您可以这样进行。

  @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);

07-25 22:35