我无法通过POST请求从JSON发送中收到信息,如下所示:
[{
"idVehicule": 1,
"vacancies": 3
}]
我有一个简单的控制器,试图从前面发送JSON,将其转换为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;
}
}
然后它只打印其中一个值。
@RequestMapping(value = "/vehicle", method = RequestMethod.POST)
public ResponseEntity<String> vehicleTest(@RequestBody testModel testModel){
System.out.println(testModel.getVacancies());
return new ResponseEntity<String>(HttpStatus.OK);;
}
在使用邮递员尝试该方法后,我不断收到此错误:
{
"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"
}
我也试过更改JSON,然后问题是该方法无法将其转换为enity,使变量“testModel”始终为null
{"testModel":{"idvehicle":1,"vacancies":3}}
删除“@RequestBoby”注释会产生与之前段落相同的问题。
任何可以帮助我找出问题的想法?感谢
答案 0 :(得分:1)
JsonProperty区分大小写。您需要使密钥名称与Json中的密钥名称完全相同。所以改变它,并检查拼写。
@JsonProperty( "idVehicule" )
答案 1 :(得分:1)
您在@JsonProperty
中指定idvehicle
为testModel
,因此请更正您要发布的JSON
:
[{
"idvehicle": 1,
"vacancies": 3
}]
接下来,您要发送{strong>数组testModel
并期待testModel
,这当然不会反序列化。
更正您要发送至JSON
的{{1}}或更改{"idvehicle": 1,"vacancies": 3}
以接受Controller
数组,如下所示:
testModel
答案 2 :(得分:0)
你{{}} POST
一组testModel
个对象(快速抱怨,类名应该以大写字母开头,所以它应该是TestModel
)但你的方法接受一个testModel
为@RequestBody
。将方法声明更改为public ResponseEntity<String> vehicleTest(@RequestBody List<testModel> testModel){