【问题标题】:JSON Object not being deserialized properly by Spring BootSpring Boot 未正确反序列化 JSON 对象
【发布时间】: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


【解决方案1】:

不应该这样: axios.post('http://localhost:8080/word', {user}) 像这样: axios.post('http://localhost:8080/word', user)

看起来用户对象被包装到另一个对象中。

另外,你可以用 postman 测试看看问题出在客户端还是服务器端。

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多