有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java控制器未将JSON转换为实体

我无法通过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);;
    }

在与postman一起尝试该方法后,我不断遇到以下错误:

{
  "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”始终为空

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

删除“@RequestBoby”注释会产生与前面段落相同的问题

有什么办法能帮我解决这个问题吗?谢谢


共 (3) 个答案

  1. # 1 楼答案

    您正在POST使用一个testModel对象数组(快速抱怨,类名应该以大写字母开头,所以应该是TestModel),但是您的方法接受一个testModel作为@RequestBody。将方法声明更改为public ResponseEntity<String> vehicleTest(@RequestBody List<testModel> testModel){

  2. # 2 楼答案

    JsonProperty区分大小写。您需要使密钥名与Json中的密钥名完全相同。所以像这样修改它,并检查拼写

    @JsonProperty( "idVehicule" )
    
  3. # 3 楼答案

    您在testModel中指定@JsonPropertyidvehicle,因此请更正您要发布到的JSON

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

    接下来,您将发送testModel数组,并期望testModel当然不会反序列化

    请更正要发送到{"idvehicle": 1,"vacancies": 3}JSON,或将Controller更改为接受testModel的数组,如下所示:

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