我有一个Spring RestController,当我从中获取数据时,它工作得很好,但是当我尝试放入非常相同的数据时,我得到了400 Bad Request.
这是我的控制器仍然可以正常工作的最简单版本(我省略了GET方法):
@RestController
@RequestMapping("/configuration/ledstrips/{name}/display")
public class DisplayController {
@ResponseBody
@RequestMapping(method = RequestMethod.PUT, produces = { "application/hal+json" })
public DisplayResource setDisplay(@PathVariable String name, @RequestBody DisplayResource display) {
return display;
}
}
这是DisplayResource:
public class DisplayResource extends ResourceSupport {
private List pixels;
public List getPixels() {
return pixels;
}
public void setPixels(List pixels) {
this.pixels = pixels;
}
}
我几乎从另一个分支复制了此代码,并且在那里工作!
我想不通!
编辑
这是GET方法:
@ResponseBody
@RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json" })
public DisplayResource getDisplay(@PathVariable String name) {
LEDStripDTO ledStripDTO;
try {
ledStripDTO = ledStripDTOService.getDTO(name);
} catch (IOException | NullPointerException exception) {
throw new LoadFailedException("Error loading LED strip:", exception);
}
Link self = linkTo(methodOn(DisplayController.class).getDisplay(name)).withSelfRel();
DisplayResource displayResource = new DisplayResource();
displayResource.add(self);
try {
displayResource.setPixels(ledStripService.getPixels(ledStripDTO));
} catch (IOException | TimeoutException | AlreadyConnectedException | NotConnectedException exception) {
throw new LoadFailedException("Error getting Information from LED strip:", exception);
}
return displayResource;
}
并产生一个结果(对于长度为1的LED灯带):
{
"pixels": [
{
"red": 0,
"green": 16,
"blue": 0
}
],
"_links": {
"self": {
"href": "http://localhost:8080/configuration/ledstrips/devled/display"
}
}
}
当我发送此消息时,无论是否包含_links段,我都会收到400错误.
解决方法:
由于它是一个PUT,因此您定义了一个农产品而不是一个消费.可能是端点不知道主体会采用哪种格式,这就是为什么它拒绝它的原因.尝试:
看了您提供的源之后,我可以看到Color类具有一个需要参数的构造函数.由于有此构造函数,Jackson库提供的默认ObjectMapper无法解组JSON字符串.尝试将默认构造函数与当前构造函数一起添加到Color类中:
public Color(int red, int green, int blue) {
this.red = setColorLimits(red);
this.green = setColorLimits(green);
this.blue = setColorLimits(blue);
}
public Color() {}
标签:spring-restcontroller,jackson,spring,java,spring-mvc
来源: https://codeday.me/bug/20191120/2040552.html