Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Failed to Convert JSON to pojo from POST request for fields that are not of type string

 public class Dog {
   private String name;
   private int weight;
     //...getters and
    //setters and constructor 
 }

Controller:

 @RequestMapping(value = "/dogs", method = RequestMethod.POST, 
 produces = "application/json")
 public void createDog(Dog dog) {
    dr.save(dog); 
 }

How come when I call the endpoint with json {"name":"bark", "weight":50} I get an error:

Failed to convert value of type 'null' to required type 'int'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [int] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type", "objectName": "dog", "field": "weight", "rejectedValue": null, "bindingFailure": true, "code": "typeMismatch"

"message": "Validation failed for object='dog'. Error count: 1

edit: I get the same issue with booleans and doubles. I guess I have to use objects not primitives?

like image 278
obesechicken13 Avatar asked Aug 16 '18 15:08

obesechicken13


2 Answers

Need to specify the @RequestBody annotation to specify we are sending DOG object as part of request body:

@RequestMapping(value = "/dogs", method = RequestMethod.POST, produces = "application/json") 
public void createDog((**@RequestBody** Dog dog) { dr.save(dog); }
like image 21
Sekhar Avatar answered Nov 07 '22 05:11

Sekhar


Add the annotation @RequestBody to the param dog in your create method

like image 192
Samuel Negri Avatar answered Nov 07 '22 04:11

Samuel Negri