In a @PostMapping call, when a list of objects is received via the @RequestBody. And this list contains Int or Double variables, if these variables are not sent in the request body json, the variables are self-initialized to 0. Instead of this, I understand that it should return bad request
This problem does not happen with the BigDecimal for example and returns bad request with this variables, or if the body of the request is an object instead of a list.
Do you know how to solve this? is it a spring problem?
Example to reproduce the problem:
data class Animal(
val name: String,
val height: Double
)
@PostMapping("/animals")
suspend fun saveAnimals(
@RequestBody request: List<Animal>
): ResponseEntity<Any> {
println(request[0].height)
return ResponseEntity.ok().build()
}
On the example above the print result will be 0 if the height is not sent on the request, but I expected this to return a bad request.
In addition to my other answer, another concept:
Why not work validation via List: https://stackoverflow.com/a/35643761/2625393
Work with this:
implementation("org.springframework.boot:spring-boot-starter-validation:2.7.5")
data class ListAnimal(
@field:Valid
val list: List<Animal>
)
data class Animal(
val name: String,
@field:NotNull
val height: Double?
)
@RestController
class Controller {
@PostMapping("/animals")
suspend fun saveAnimals(@RequestBody @Valid request: ListAnimal): ResponseEntity<Any> {
println(request.list)
return ResponseEntity.ok().build()
}
}
POST http://localhost:8080/animals
Content-Type: application/json
{
"list": [
{
"name": "name"
}
]
}