英文:
Spring: Error 400 with @RequestBody and JSON
问题
以下是代码部分的翻译:
我有以下的代码部分。当我发送HTTP请求时,我收到一个与carCoordinates字段相关的400错误(如果我删除它,一切正常)。它应该是一个double类型的列表。
另外,当我将carCoordinates的名称更改为carcoordinates而不更改getter的名称时,请求被成功接收,但是我无法获取数据,因为getter与对象没有关联(为null)。如果我将getter的名称更改为getCarcoordinates以匹配该字段,它就不再起作用了。
有任何想法为什么它不起作用?
CarEvent.java:
public class CarEvent {
@JsonProperty("carCoordinates")
protected List<Double> carCoordinates;
...
public void setCarCoordinates(Coordinate c) {
...
}
public List<Double> getCarCoordinates() {
return carCoordinates;
}
}
发送的JSON数据如下:
{
"id": [6001556, 631016236, 125899724],
"speed": "0",
"carCoordinates": [56.477369, 26.64477, 56.466177, 26.651258, 80.545048, 50.614582],
"num": "5"
}
被请求的服务器类是:
@RequestMapping(method = RequestMethod.POST, value = "/car-action", produces = "application/json;charset=UTF-8")
@ResponseBody
public String CarAction(@RequestBody CarEvent requestBody, @RequestHeader HttpHeaders httpHeaders) {
...
}
英文:
I have the following parts of code. When I send the HTTP request, I get an error 400 related to carCoordinates field (if I remove it, everything is fine). It is supposed to be a list of double.
Also, when I change the name carCoordinates to carcoordinates without changing getter name, the request is well received but I can't get the data since getter is not linked with the object (null). If I change the getter name to getCarcoordinates to match the field, it doesn't work anymore.
Any ideas why it does not work?
CarEvent.java :
Public class CarEvent {
@JsonProperty("carCoordinates")
protected List carCoordinates;
...
public void setCarCoordinates(Coordinate c) {
...
}
public List getCarCoordinates() {
return CarCoordinates;
}
}
The JSON sent is :
{
"id": [006001556, 631016236, 125899724],
"speed": "0",
"carCoordinates": [56.477369, 26.64477, 56.466177, 26.651258, 80.545048, 50.614582],
"num": "5"
}
The server class that is requested is:
@RequestMapping(method = RequestMethod.POST, value = "/car-action", produces = "application/json;charset=UTF-8")
@ResponseBody
public String CarAction(@RequestBody CarEvent requestBody, @RequestHeader HttpHeaders httpHeaders) {
...
}
答案1
得分: 2
问题可能出在你的 setter 方法上。你的字段类型是 List
,但是 setter 接受的参数类型是 Coordinate
的对象。根据你的 JSON 请求,我认为应该这样修改:
public void setCarCoordinates(List<Coordinate> c) {
this.carCoordinates = c;
}
英文:
The problem probably is your setter method. Your field is of type List
but the setter takes in an Object of Coordinate
. Based on your json request I think it should be:
public void setCarCoordinates(List c) {
this.carCoordinates = c;
}
答案2
得分: 2
你的CarEvent
具有错误参数的setter方法。
要么创建一个名为Coordinate
的类并将其扩展为List,要么按以下方式更新:
public void setCarCoordinates(List cordinates) {
...
}
英文:
Your CarEvent
<br>
has setter method with wrong argument.<br>
either create a class Coordinate
and extend to List or
Update as below:
public void setCarCoordinates(List cordinates) {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论