我正在使用Spring Boot并尝试接受POST。
我收到错误消息
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not construct instance of biz.ianw.ukData.restServer.Controller$Car:
no suitable constructor found, can not deserialize from Object value (missing default constructor
or creator, or perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@24b515ad; line: 1, column: 2]; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of biz.ianw.ukData.restServer.Controller$Car:
no suitable constructor found, can not deserialize from Object value (missing default constructor
or creator, or perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@24b515ad; line: 1, column: 2]
我测试的代码是:
public class Car {
private String color;
public Car() {}
public Car(String color) { this.color = color; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
}
@RequestMapping(value="/search", method=RequestMethod.POST)
public @ResponseBody String doSearch(@RequestBody Car data) {
logger.info("in search: {}", data);
return new String("Done.");
}
我正在使用jQuery发送POST:
datablock.urlpath = "search";
datablock.type = "POST";
datablock.contentType = "application/json; charset=utf-8";
datablock.data = { color: "Blue" };
$.ajax({
type: datablock.type,
url: server + datablock.urlpath,
contentType: datablock.contentType,
data: JSON.stringify(datablock.data)
})
.then(function (data) {
console.log("ajaxCall success: " + JSON.stringify(datablock) + " -> " + JSON.stringify(data));
})
.fail(function (xhr, status, err) {
var response = JSON.parse(xhr.responseText);
console.log("ajaxCall failure: " + JSON.stringify(datablock) + " -> " + response.message);
});
默认构造函数存在且标题和正文似乎正确,显示了预期的内容类型和有效负载:
所以我有点不知所措地解释错误信息。有什么建议我错过了吗?
答案 0 :(得分:1)
问题是目标类,在这种情况下,Car 不能是非静态内部类。它不像在问题中那样嵌入在Controller类中。
详细信息在here中,但归结为Java添加内部类的方式意味着他们没有Jackson所需的默认构造函数。
答案 1 :(得分:1)
我遇到了同样的问题,但是我和你之间存在细微差别,我从未添加过默认构造函数,在添加相同内容之后,应用就像Gem一样。