简体   繁体   中英

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. The field of the object are just null .

Here is my 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;
    }
}

Here is my axios.post call in handleSubmit:

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);
        })
}

Here is 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; 
}

}

The Payload appears as {sentence: "hello", word: "world"}

Shouldn't this: axios.post('http://localhost:8080/word', {user}) be like this: axios.post('http://localhost:8080/word', user)

Looks like user object is wrapped into another one.

Also, you can test with postman to see if the problem is on client or server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM