I'm just starting to use kotlin along side with Spring Boot to develop a simple web application.
Let´s take a simple data class object
@Entity
data class User (name: String) {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
var id: Long = -1
}
and a Controller
@RequestMapping(method = arrayOf(RequestMethod.POST))
fun createUser (@RequestBody user: User): User {
return userService.createUser(user)
}
Well, making a request with any request body would just throw an http 400 error
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
To eliminate this error I found out that we need to give some default values to the constructor arguments so:
name: String = ""
or maybe:
name: String? = null
Now, there is absolutely no validation of the input that goes on the response body, meaning that, if the JSON present in there does not respect the syntax of the User class, the default values will be used and stored in the database.
Is there any way to validate the request body JSON input to throw a bad request if it does not comply with the User class arguments without having to do it manually?
In this example there is only one argument but with larger classes manually does not seems like a good way to go
Thanks in advance