[英]How to deserialize nested Kotlin objects on the RestController?
在 Spring 應用程序的RestController
組件中,我有 function 需要嵌套的 object 作為參數。
這是代碼
@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 應該足夠聰明,可以反序列化兩個嵌套的 object,但似乎有些麻煩。 因為答案是:
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 是一種不好的做法,我會推薦一個帶有request body
的POST
方法,以便能夠反序列化 object
@PostMapping(path = ["/hi"])
fun sayHello(@RequestBody userRequest: UserRequest): String {
return "Hello ${userRequest.name} - ${userRequest.nested!!.nestedValue}"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.