user2690047 user2690047 - 2 months ago 18
JSON Question

Java Controller not transforming for JSON to entity

I have been unable to receive information from a JSON send through a POST request, that looks something like this:

[{
"idVehicule": 1,
"vacancies": 3
}]


I have a simple controller that tries to get that JSON sent from front, convert it into a testModel:

import com.fasterxml.jackson.annotation.JsonProperty;

public class testModel {

@JsonProperty( "idvehicle" )
private int idvehicle;
@JsonProperty( "vacancies" )
private String vacancies;

public int getIdvehicle() {
return idvehicle;
}
public void setIdvehicle(int idvehicle) {
this.idvehicle = idvehicle;
}
public String getVacancies() {
return vacancies;
}
public void setVacancies(String vacancies) {
this.vacancies = vacancies;
}

}


And then it just prints one of its values.

@RequestMapping(value = "/vehicle", method = RequestMethod.POST)
public ResponseEntity<String> vehicleTest(@RequestBody testModel testModel){
System.out.println(testModel.getVacancies());
return new ResponseEntity<String>(HttpStatus.OK);;
}


After trying the method with postman, i keep getting this error:

{
"timestamp": 1472819769941,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Can not deserialize instance of testModel out of START_ARRAY token\n at [Source: java.io.PushbackInputStream@646345e6; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of testModel out of START_ARRAY token\n at [Source: java.io.PushbackInputStream@646345e6; line: 1, column: 1]",
"path": "/vehicle"
}


I have also tried changing the JSON and then the problem is that the method is unable to convert it into the enity, making the variable "testModel" always null

{"testModel":{"idvehicle":1,"vacancies":3}}


Removing the "@RequestBoby" annotation gives the same problem that the paragraph before.

Any ideas that could help me figure out the problem? Thanks

Answer

You are specifying @JsonProperty as idvehicle in your testModel so correct the JSON you are posting to:

 [{
     "idvehicle": 1,
     "vacancies": 3
 }]

Next, you are sending the array of testModel and expecting testModel which will of-course will not deserialize.

Either correct the JSON you are sending to {"idvehicle": 1,"vacancies": 3} or change the Controller to accept array of testModel as follows:

@RequestMapping(value = "/vehicle", method = RequestMethod.POST)
public ResponseEntity<String> vehicleTest(@RequestBody List<testModel> testModel){

        return new ResponseEntity<String>(HttpStatus.OK);;
}
Comments