gpt4 book ai didi

Java Controller 未将 JSON 转换为实体

转载 作者:行者123 更新时间:2023-12-02 03:23:35 25 4
gpt4 key购买 nike

我无法从通过 POST 请求发送的 JSON 中接收信息,如下所示:

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

我有一个简单的 Controller ,尝试获取从前面发送的 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,然后问题是该方法无法将其转换为实体,使得变量“testModel”始终为 null

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

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

有什么想法可以帮助我解决这个问题吗?谢谢

最佳答案

您正在指定@JsonPropertyidvehicle在你的testModel所以更正JSON您要发布到:

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

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

更正JSON您正在发送至{"idvehicle": 1,"vacancies": 3}或更改 Controller接受 testModel 的数组如下:

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

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

关于Java Controller 未将 JSON 转换为实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com