首页 > 解决方案 > 如何反序列化 RestController 上的嵌套 Kotlin 对象?

问题描述

RestControllerSpring 应用程序的组件中,我具有需要嵌套对象作为参数的函数。

这是代码

@RestController
class AdController {

    @GetMapping(path = ["/hi"])
    fun sayHello(userRequest: UserRequest): String {
        return  "Hello ${userRequest.name} - ${userRequest.nested!!.nestedValue}"
    }
}

data class UserRequest(val name: String, val nested: NestedObject)
data class NestedObject(var nestedValue: String)

此 API 由客户端调用,将所有参数作为查询字符串传递

curl localhost:8080/hi\?name=Tom&nested.nestedValue=Berlin

Spring 应该足够聪明地反序列化两个嵌套对象,但似乎有些麻烦。因为答案是:

Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Parameter specified as non-null is null

为了让它发挥作用,我不得不放弃使用 nice&save Kotlin 语法并制作一切nullable.

class UserRequest {
    var name: String? = null
    var nested: NestedObject? = null
}

class NestedObject {
    var nestedValue: String? = null
}

通过这种方式它可以工作,但我宁愿在我的模型上有一个更明确的可空性。

标签: javaspringspring-bootspring-mvckotlin

解决方案


问题是请求方法,在这种情况下使用 GET 是一种不好的做法,我会推荐一种POST能够request body反序列化对象的方法

@PostMapping(path = ["/hi"])
fun sayHello(@RequestBody userRequest: UserRequest): String {
    return  "Hello ${userRequest.name} - ${userRequest.nested!!.nestedValue}"
}

推荐阅读