java - 如何反序列化 RestController 上的嵌套 Kotlin 对象?
问题描述
在RestController
Spring 应用程序的组件中,我具有需要嵌套对象作为参数的函数。
这是代码
@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
}
通过这种方式它可以工作,但我宁愿在我的模型上有一个更明确的可空性。
解决方案
问题是请求方法,在这种情况下使用 GET 是一种不好的做法,我会推荐一种POST
能够request body
反序列化对象的方法
@PostMapping(path = ["/hi"])
fun sayHello(@RequestBody userRequest: UserRequest): String {
return "Hello ${userRequest.name} - ${userRequest.nested!!.nestedValue}"
}
推荐阅读
- git - 删除每个子模块的特定标签
- c# - 按类/段落值查找值
- ios - 在 iOS 上的 React Native 原生模块中注册观察者(NSNotificationCenter)
- html - 屏幕阅读器如何阅读
如果默认情况下它们不是可聚焦的标签?
- html - div 内的 div 在特定分辨率/缩放级别上溢出边界
- python - Tensorflow 没有“核心”属性
- excel - 根据单元格值将 pandas DataFrame 导出到 excel 中
- c - 通过信号 SIGQUIT 唤醒休眠的守护进程
- c++ - 如何在 MacOS Objective C / C++ 中将 UUID 转换为 16 字节 UInt8 数组
- python - 循环遍历Python中不同文件夹中的文件