[英]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.