java - 如何反序列化 RestController 上嵌套的 Kotlin 对象?

标签 java spring spring-boot spring-mvc kotlin

在 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/

相关文章:

java - Spring Boot Async ResultSet 已关闭

spring - 使用保管库保护 Spring Cloud 配置凭据

spring-boot - 对象未存储在 Redis 缓存中

java - 如何从字符串中替换 "}"?

java - 整理/管理数据以在 Web 应用程序中填充 "live activity feeds"

java - 如何将 web 服务的 xml 响应转换为所需的 xml 格式?

java - Spring 注解扫描优化

java - bean 类的属性 'tempsReglementaireBusiness' 无效

java - 最大化窗口时多次调用 PaintComponent 方法

java - 多部分文件到 .zip