如何将数组发送到 Spring Rest?我尝试了以下方法,但没有成功
JavaScript:
function postTopic(){
self.data.blogTopicsArr.push({
options: {
"title": self.title.value,
"details": self.topicDetails.value,
"username": "Guest user",
"userImage": "assets/img/spiritual-icon4.png",
"day_posted": new Date().toLocaleString()
}
});
$.ajax({
url: "/new_topic",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(self.data.blogTopicsArr),
success: function (res) {
},
error: function (err) {
}
});
}
主题 Bean 类:
@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title")
private String title;
@Column(name = "details")
private String details;
@Column(name = "username")
private String username;
@Column(name = "userImage")
private String userImage;
@Column(name = "day_posted")
private Date day_posted;
//Getters and Setters
}
Spring 休息:
@RequestMapping(path = "/new_topic", method = RequestMethod.POST)
public ResponseEntity new_topic(@RequestBody List[] topics) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("success", "topic added");
return new ResponseEntity(headers, HttpStatus.OK);
}
我收到错误:{"statusCode":400,"body":{"timestamp":1484506636823,"status":400,"error":"错误请求","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"缺少必需的请求正文:public org.springframework.http.ResponseEntity Seconds47.rest API.Topics.new_topic(java.util.List[]) 抛出 java.lang.Exception","path":"/new_topic"}}}
如何解决这个问题?
更新:在上面添加主题 bean 类以及我在该类中使用的字段
请您参考如下方法:
尝试使用
@RequestMapping(path = "/new_topic", method = RequestMethod.POST)
public ResponseEntity new_topic(@RequestBody List<HashMap<String, Object>> topics) throws Exception
并打印出主题中的所有输入。如果您确实获得任何值,则需要将其替换为
@RequestMapping(path = "/new_topic", method = RequestMethod.POST)
public ResponseEntity new_topic(@RequestBody List<Topic> topics) throws Exception
与Topic类的相关结构。
public class Topic{
OptionsBean options;
...
//getters and setters
...
}
public class OptionsBean{
String title;
String details;
String username;
String userImage;
String day_posted;
...
//getters and setters
...
}