简体   繁体   English

JSON Object 没有被 Spring 引导正确反序列化

[英]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. 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 . object 的字段只是null

Here is my Controller:这是我的 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:这是我在句柄提交中的 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);
        })
}

Here is WordSearch.java:这是 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"}有效载荷显示为{sentence: "hello", word: "world"}

Shouldn't this: axios.post('http://localhost:8080/word', {user}) be like this: axios.post('http://localhost:8080/word', user)不应该这样: axios.post('http://localhost:8080/word', {user})是这样的: axios.post('http://localhost:8080/word', user)

Looks like user object is wrapped into another one.看起来用户 object 被包装到另一个用户中。

Also, you can test with postman to see if the problem is on client or server side.此外,您可以使用 postman 进行测试,看看问题出在客户端还是服务器端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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