[英]JSON Object not being deserialized properly by Spring Boot
I am trying to make a post request with Axios to my api, but the JSON is not being deserialized properly into a java object, despite adding the @ResponseBody
annotation. object 的字段只是null
。
这是我的 Controller:
@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;
}
}
这是我在句柄提交中的 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;
}
}
有效载荷显示为{sentence: "hello", word: "world"}
不应该这样: axios.post('http://localhost:8080/word', {user})
是这样的: axios.post('http://localhost:8080/word', user)
看起来用户 object 被包装到另一个用户中。
此外,您可以使用 postman 进行测试,看看问题出在客户端还是服务器端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.