小编Mig*_*ães的帖子

Kotlin 和 Spring Boot 请求正文验证

我刚刚开始使用 kotlin 和 Spring Boot 来开发一个简单的 Web 应用程序。

让我们来看一个简单的数据类对象

@Entity  
data class User (name: String) {  
  @Id @GeneratedValue(strategy = GenerationType.AUTO)  
  var id: Long = -1  
}  
Run Code Online (Sandbox Code Playgroud)

和一个控制器

@RequestMapping(method = arrayOf(RequestMethod.POST))
fun createUser (@RequestBody user: User): User {
    return userService.createUser(user)
}
Run Code Online (Sandbox Code Playgroud)

好吧,使用任何请求正文发出请求只会引发 http 400 错误 no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException

为了消除这个错误,我发现我们需要为构造函数参数提供一些默认值,因此:

name: String = ""
Run Code Online (Sandbox Code Playgroud)

或者可能:

name: String? = null …
Run Code Online (Sandbox Code Playgroud)

validation spring httprequest kotlin spring-boot

5
推荐指数
1
解决办法
5082
查看次数

标签 统计

httprequest ×1

kotlin ×1

spring ×1

spring-boot ×1

validation ×1