Issue
Controller method:
@PostMapping(value = "/template")
ResponseEntity<Object> createtemplate(@Valid @RequestBody Template template) {
return templateService.createCsvTemplate(template);
}
Object class:
@Getter
@Setter
public class Template {
@Min(value = 1, message = "Please provide a valid ID, must be greater than 0")
private int id;
}
POST input:
{
"id": 5.5
}
The application accepts this value, setting the value of id
to 5. How can I reject accepting such fractional values,
throwing an error when one is received?
Solution
By default, jackson serializes decimal value as integer because ACCEPT_FLOAT_AS_INT
flag is true by default. Set ACCEPT_FLOAT_AS_INT
to false should fix your problem. And your need to handle throwing exception also.
ObjectMapper.configure(DESERIALIZATION_FEATURE.ACCEPT_FLOAT_AS_INT, false);
You can set configuration this way
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper configureObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DESERIALIZATION_FEATURE.ACCEPT_FLOAT_AS_INT, false);
return mapper;
}
}
Answered By - Eklavya
Answer Checked By - Timothy Miller (JavaFixing Admin)