【发布时间】:2021-06-08 01:32:10
【问题描述】:
我正在尝试使用 Axios 向我的 api 发出 post 请求,但 JSON 没有被正确反序列化为 java 对象,尽管添加了 @ResponseBody 注释。对象的字段就是null。
这是我的控制器:
@RestController
class WordSearchController {
private long count;
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping(
value = "/word",
consumes = {MediaType.APPLICATION_JSON_VALUE}
)
public long Search (@RequestBody WordSearch wordsearch) {
count = wordsearch.search();
return count;
}
}
这是我在 handleSubmit 中的 axios.post 调用:
class SubmitForm extends Component {
state = {
sentence: '',
word: '',
};
handleSubmit = event => {
event.preventDefault();
console.log(this.state.sentence);
const user = {
sentence: this.state.sentence,
word: this.state.word,
}
console.log(user)
axios.post('http://localhost:8080/word', {user})
.then(res=>{
console.log(res);
console.log(res);
})
}
这里是 WordSearch.java:
public class WordSearch {
@JsonProperty("sentence")
private String sentence;
@JsonProperty("word")
private String word;
public void setSentence(String sentence) {
this.sentence = sentence;
}
public void setWord(String word) {
this.word = word;
}
public String getSentence() {
return this.sentence;
}
public String getWord() {
return this.word;
}
public long search() {
Pattern word_pattern = Pattern.compile("\\b" + (this.word) + "\\b");
Matcher countWord = word_pattern.matcher(this.sentence);
long count = countWord.results().count();
/* int count = 0;
String [] words = (this.sentence).split(" ");
for (int i = 0; i < words.length; i++) {
if ((words[i]).equals(this.word)) {
count++;
}
}
*/
return count;
}
}
Payload 显示为 {sentence: "hello", word: "world"}
【问题讨论】:
-
请显示您的对象类和有效负载。
-
更新了对象类和有效负载
标签: javascript java html json spring-boot