我在将JSON数组发布到Spring Boot @RequestMapping Rest控制器时遇到问题。得到400错误请求。有任何建议如何纠正?
JQuery .ajax post
var sData = ["15957.028", "16356.175", "16937.155", "17564.315", "17942.480", "17760.259", "16572.306", "16746.408", "17339.681", "17946.216"]
$.ajax({
type: "POST",
url: "/regression",
data: JSON.stringify({"sdata": sData}),
contentType: 'application/json',
headers: { 'X-CSRF-Token': token },
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown, jqXHR.error());
},
success: function(){
}
});
@RestController
@RequestMapping(value="/regression", method = RequestMethod.POST)
public HashMap<String, String> results(@RequestBody List<String> series ) {
HashMap<String, String> results = new HashMap<String, String>();
return results;
}
响应错误
responseText: "{"timestamp":1424834682223,"error":"Bad Request","status":400,"message":""}"
答案 0 :(得分:0)
您需要将List包装到另一个类中,如下所示
class SeriesWrapper{
@Getter @Setter private List<String> series;
}
您的控制器变为
@RequestMapping(value="/regression", method = RequestMethod.POST)
public HashMap<String, String> results(@RequestBody SeriesWrapper series ) {
HashMap<String, String> results = new HashMap<String, String>();
return results;
}
和你的sData
var sData = {series : ["15957.028", "16356.175", "16937.155", "17564.315", "17942.480", "17760.259", "16572.306", "16746.408", "17339.681", "17946.216"]};
答案 1 :(得分:0)
您尝试发布的sData不是JSON格式,因为您尝试将其发布为JSON
data: JSON.stringify({"sdata": sData}),
contentType: 'application/json',
因此 400错误。
正确的JSON格式示例:
{ "firstname" : firstname, "lastname" : lastname, "email": email, "phone": phone, "company": company};