具有非Enum类型字段参数构造函数的Kotlin类无法反序列化

时间:2019-12-03 04:32:39

标签: spring kotlin jackson resttemplate

我不确定这是否是Kotlin或Spring&Jackson框架/库的错误,但是kotlin类无法从RestTemplate响应中反序列化-当且仅当它们的构造函数恰好具有一个参数不是枚举类型时声明为字段。

示例:

class Foo(
    tempVar: Long? = null
) {
    var id: Long
}

正常反序列化,而低于以下则不起作用。

class Bar(
    tempVar: SomeEnum? = null
) {
    var id: Long
}

一个简单的场景:

@RestController
class SampleController (
    private val restTemplate: RestTemplate
) {
    // this works
    @RequestMapping("/foo1")
    fun foo(foo: Foo) = foo

    // this works
    @RequestMapping("/bar1")
    fun bar(bar: Bar) = bar

    // this works
    @RequestMapping("/foo2")
    fun fooTwo() = restTemplate.postForObject("http://localhost:8080/api", mapOf<String, String>(), Foo::class.java)

    // This fails.
    @RequestMapping("/bar2")
    fun barTwo() = restTemplate.postForObject("http://localhost:8080/api", mapOf<String, String>(), Bar::class.java)

    @RequestMapping("/api")
    fun api() = Bar().apply { // notice how Bar actually has a valid NoArg constructor
        id = 1
    }
}

当您调用/bar2时,您会遇到一个类似HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type 'SomeEnum'的错误,尽管tempVar甚至不是一个字段,并且提供了默认值,并且Jackson应该使用NoArgs构造函数,然后首先使用设置器设置值。

我在这里错过了什么吗?还是应该将其作为错误报告发布到Spring或JetBrains?

说明问题的示例存储库:https://github.com/gyuhyeon/KotlinSerializationIssueDemo

0 个答案:

没有答案