gpt4 book ai didi

java - 如何将javascript数组传递给Spring Data Rest

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:35 24 4
gpt4 key购买 nike

如何将数组发送到 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
...
}

关于java - 如何将javascript数组传递给Spring Data Rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com