在 Spring 应用程序的 RestController
组件中,我有一个需要嵌套对象作为参数的函数。
这是代码
@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 语法,并让所有内容都可空
。
class UserRequest {
var name: String? = null
var nested: NestedObject? = null
}
class NestedObject {
var nestedValue: String? = null
}
通过这种方式它可以工作,但我宁愿在我的模型上有更明确的可空性。
最佳答案
问题在于请求方法,在这种情况下使用 GET 是一种不好的做法,我会推荐带有请求正文
的 POST
方法,以便能够反序列化对象
@PostMapping(path = ["/hi"])
fun sayHello(@RequestBody userRequest: UserRequest): String {
return "Hello ${userRequest.name} - ${userRequest.nested!!.nestedValue}"
}
关于java - 如何反序列化 RestController 上嵌套的 Kotlin 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996324/