Spring 引导 - 自定义 JsonDeserializer 被忽略

Spring Boot - Custom JsonDeserializer is ignored

我正在尝试将自定义 Jackson 反序列化器(class“com.fasterxml.jackson.databind.JsonDeserializer”)应用于来自需要自定义反序列化的第三方库的 bean。我的自定义解串器是用 Kotlin 编写的:

@JsonComponent
class CustomDeserializer: JsonDeserializer<ThirdPartyBean> {

    constructor(): super() {
        println("CustomDeserializer registered")
    }

    override fun deserialize(parser: JsonParser?, context: DeserializationContext?): ThirdPartyBean? {
        // Custom deserialization
    }

    override fun handledType(): Class<*> {
        return ThirdPartyBean::class.java
    }
}

我已尝试执行以下所有操作(实际上是它们的所有组合):

  1. 按原样使用 class:我可以看到解串器已被拾取 - 我可以看到正在打印“CustomSerializer registered”。
  2. 用自定义反序列化器注释使用 ThirdPartyBean 的字段(见下文)
  3. 向 ApplicationContext 显式注册反序列化器(见下文)

广告 2:

@JsonDeserialize(using = CustomDeserializer::class)
fun getThirdPartyBean(): ThirdPartyBean = thirdPartyBean

广告 3:

@Bean
fun jacksonBuilder(): Jackson2ObjectMapperBuilder {
    return Jackson2ObjectMapperBuilder()
        .deserializers(CustomDeserializer())
}

无论我尝试过什么,在尝试序列化一个 bean 时,我总是会收到此客户端错误,该 bean 在其他属性中包含 属性 类型“ThirdPartyBean”:

    org.springframework.core.codec.CodecException: Type definition error: [simple type, class com.example.ThirdPartyBean]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.ThirdPartyBean` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Spring 引导版本为 2.3.1。我对如何解决这个问题无能为力,我们将不胜感激。

我自己设法解决了这个问题。不过,我很确定 must/should 会有一个更简单的解决方案,所以我很高兴听到任何建议。我通过在 WebClient 设置中手动注册包含我的 CustomDeserializer 的 Jackson 模块解决了这个问题:

@SpringBootApplication
@EnableWebFlux
class MyApplication: WebFluxConfigurer {

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    @Bean
    fun webClient(): WebClient {
        val customDeserializerModule = SimpleModule()

        customDeserializerModule.addDeserializer(ThirdPartyBean::class.java, CustomDeserializer())
        objectMapper.registerModule(customDeserializerModule)

        return WebClient
            .builder()
            .codecs { it.defaultCodecs().jackson2JsonDecoder(Jackson2JsonDecoder(objectMapper)) }
            .build()
    }
}