如何解决错误:无效的JSON输入:无法从START_ARRAY令牌中反序列化Topic实例

马兹纳

我正在开发一个使用Springboot Rest API和ReactJS前端的调查应用程序,我面临着一个看似无法解决的问题。在我的Springboot应用程序中,我有一个名为Topic的bean,其编写如下:

@Entity
public class Topic {
    @Id
    @GeneratedValue
    private Long id;

    private String question;

    @NotNull
    @Size(min=3, max=20)
    private String topic;

    @Column(precision=4, scale=1)
    private double npm = 0;

    @OneToMany(mappedBy = "topic")
    private Set<Submission> submissions;

    public Topic()
    {
        super();
    }

    public Topic(Long id, String topic, double npm)
    {
        super();
        this.id = id;
        this.setTopic(topic);
        this.setNpm(npm);
    }

    public Long getID()
    {
        return this.id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    /**
     * @return the topic
     */
    public String getTopic() {
        return topic;
    }

    /**
     * @param topic the topic to set
     */
    public void setTopic(String topic) {
        this.topic = topic;
    }

    /**
     * @return the npm
     */
    public double getNpm() {
        return npm;
    }

    /**
     * @param npm the npm to set
     */
    public void setNpm(double npm) {
        this.npm = npm;
    }

    /**
     * @return the question
     */
    public String getQuestion() {
        return question;
    }

    /**
     * @param question the question to set
     */
    public void setQuestion(String question) {
        this.question = question;
    }

}

和一个Repository类:

@Repository
public interface TopicRepository extends JpaRepository<Topic, Long>{

    @Transactional
    @Modifying
    @Query("UPDATE Topic SET npm = ?1 WHERE id = ?2")
    public void updateNpm(double newNpm, long id);

    @Query("SELECT topic FROM Topic")
    public List<String> getTopics();

}

最后,我的Controller类如下(我省略了不会引起问题的方法):

@RestController
public class TopicResource {

    @Autowired
    private TopicRepository topicRepository;

    @CrossOrigin
    @PostMapping("/topics")
    public void createTopic(@RequestBody Topic topic)
    {
        Topic savedTopic = topicRepository.save(topic);
    }
}

在我的React应用程序中,我正在从以下组件类发出POST请求:

import React, { Component } from 'react';
import './Styling/createsurvey.css'

class CreateSurvey extends Component {

    constructor () {
        super();
        this.state = {
            topic: '',
            question: ''
        };

        this.handleTopicChange = this.handleTopicChange.bind(this);
        this.handleQuestionChange = this.handleQuestionChange.bind(this);
        //this.printState = this.printState.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleTopicChange(e) {
        this.setState({
            topic: e.target.value
        });
    }

    handleQuestionChange(e) {
        this.setState({
            question: e.target.value
        });
    }

    handleSubmit(event) {
        event.preventDefault();

        console.log(this.state.topic);
        console.log(this.state.question);

        fetch('http://localhost:8080/topics', {
            method: 'post',
            headers: {'Content-Type':'application/json'},
            body: {
                "npm": "0",
                "topic": "Turkey",
                "question": "How is life here",
                "submissions": {}
            }
           });


    }

    render() {
        return(
           <div>
               <form onSubmit={this.handleSubmit}>
                   <h2>Create a new Survey</h2>
                   <br></br>
                   <div className="form-group">
                        <label><strong>Enter the survery topic: </strong></label>
                        <br></br>
                        <input 
                        className="form-control" 
                        placeholder="Enter a cool topic to ask a question about"
                        align="left"
                        onChange={this.handleTopicChange}>        
                        </input>
                   </div>
                   <div className="form-group">
                        <label><strong>Enter a survey question: </strong></label>
                        <br></br>
                        <textarea
                        className="form-control" 
                        placeholder="Ask your question here. The customer will give an answer on a scale from 1 to 10."
                        align="left"
                        rows="3"
                        onChange={this.handleQuestionChange}>        
                        </textarea>
                   </div>
                   <div className="form-group">
                    <button type="submit" className="btn btn-primary">Submit Your Question</button>
                   </div>   
            </form>
           </div>
        );
    }

}

export default CreateSurvey;

我面临以下错误:

2020-03-03 01:15:17.862 DEBUG 17816 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : POST "/topics", parameters={}
2020-03-03 01:15:17.862 DEBUG 17816 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.recommend.me.springboot.rest.recommendme.topic.TopicResource#createTopic(Topic)
2020-03-03 01:15:17.867 DEBUG 17816 --- [nio-8080-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Could not resolve parameter [0] in public void com.recommend.me.springboot.rest.recommendme.topic.TopicResource.createTopic(com.recommend.me.springboot.rest.recommendme.topic.Topic): Invalid JSON input: Cannot deserialize instance of `com.recommend.me.springboot.rest.recommendme.topic.Topic` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.recommend.me.springboot.rest.recommendme.topic.Topic` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 1, column: 1]

有人可以指出我的请求做错了什么吗?我尝试了所有形式的JSON请求格式,但似乎无济于事。

黄谢赫

在将序列化主题对象发送到控制器时,需要对身体进行字符串化处理。JSON.stringify应该可以解决问题。

检查以下代码并链接到jsfiddle

fetch('http://localhost:8080/topics', {
            method: 'post',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({
                "npm": "0",
                "topic": "Turkey",
                "question": "How is life here",
                "submissions": {}
            })
           })

    .then(function (response) {
    return response.json();
})
    .then(function (result) {
    alert(result)
})
    .
catch (function (error) {
    console.log('Request failed', error);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Json Mapping Exception无法从START_ARRAY令牌中反序列化实例

ObjectMapper无法反序列化-无法从START_ARRAY令牌反序列化....的实例

无法在Spring Webservice中从START_ARRAY令牌中反序列化对象的实例

杰克逊错误:无法从START_ARRAY令牌中反序列化`java.lang.String`的实例

无法从START_ARRAY令牌中反序列化java.util.HashMap的实例

无法从START_ARRAY令牌中反序列化java.util.LinkedHashMap的实例

无法从 START_ARRAY 令牌中反序列化 SaleListDTO 的实例

Java REST API:无法从START_ARRAY令牌中反序列化Object的实例

无法从 START_ARRAY 令牌中反序列化 <Object> 的实例 - webClient

将JSON转换为对象会引发JsonMappingException“无法从START_ARRAY令牌中反序列化类的实例”

无法从 START_ARRAY 令牌反序列化 java.lang.Boolean 的实例

无法反序列化模型实例。*来自START_ARRAY令牌\ n,位于

无法使用START_ARRAY令牌反序列化Object的实例

无法使用START_ARRAY令牌反序列化我的软件包的实例

无法从START_ARRAY令牌中反序列化com.example.million.model.Domain的实例

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_ARRAY令牌中反序列化Object的实例

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_ARRAY令牌中反序列化对象实例-JAVA

如何解决此错误“ JSON分析错误:无法从START_OBJECT中反序列化java.lang.Integer实例

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从 START_ARRAY 令牌反序列化“Todo”的实例

使用 ModelMapper 反序列化 Json 時如何修復錯誤 START_ARRAY 令牌?

JSON解析错误:无法从START_OBJECT令牌中反序列化java.util.ArrayList实例

如何解决反序列化中的此错误?

无法序列化START_ARRAY令牌之外的类的实例\ n

com.fasterxml.jackson.databind.exc.MismatchedInputException:可以反对的不是反序列化实例出来START_ARRAY令牌

Json 无法反序列化 Spring 中的实例错误

JSON反序列化引发异常-无法从START_OBJECT令牌中反序列化java.util.ArrayList的实例

无法读取JSON:无法从START_OBJECT令牌中反序列化hello.Country []实例

请问sdk如何解决反序列化错误

无法从START_OBJECT令牌中反序列化int []实例