I'm unsure if this is a bug with Kotlin or Spring & Jackson frameworks/libraries, but kotlin classes fail to deserialize from RestTemplate responses - when and only when they have a constructor which happens to have a parameter that aren't declared as a field while being type Enum.
Example:
class Foo(
tempVar: Long? = null
) {
var id: Long
}
deserializes normally while below doesn't work.
class Bar(
tempVar: SomeEnum? = null
) {
var id: Long
}
A simple scenario:
@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
}
}
When you call /bar2
, you get a wonderful error like HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type 'SomeEnum'
although tempVar isn't even a field, and it has a default value supplied, and Jackson should be using the NoArgs constructor and then using setters to set the values in the first place.
Am I missing something here? Or should I post this as a bug report to Spring or JetBrains?
sample repository illustrating the issue: https://github.com/gyuhyeon/KotlinSerializationIssueDemo