首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Boot未正确反序列化JSON对象

Spring Boot未正确反序列化JSON对象
EN

Stack Overflow用户
提问于 2021-03-10 13:56:21
回答 1查看 66关注 0票数 1

我尝试使用Axios向我的应用程序接口发出post请求,但是尽管添加了@ResponseBody注释,但JSON并没有被正确地反序列化为java对象。该对象的字段仅为null

这是我的控制器:

代码语言:javascript
复制
@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调用:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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"}

EN

回答 1

Stack Overflow用户

发布于 2021-03-10 15:39:11

axios.post('http://localhost:8080/word', user)axios.post('http://localhost:8080/word', {user})应该是这样的吗?

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

此外,您还可以使用postman进行测试,以查看问题出在客户端还是服务器端。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66559122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档