java - JSON 解析错误 : Can not construct instance of io. starter.topic.Topic

标签 java spring-boot

我正在学习 Spring Boot 并制作了一个演示,但是当我发布一个添加对象的请求时,它不起作用!

错误信息是:

{
    "timestamp": 1516897619316,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "JSON parse error: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@1ff3f09a; line: 2, column: 9]",
    "path": "/topics/"
}

我的实体:

public class Topic {
    private String id;
    private String name;
    private String author;
    private String desc;

    public Topic(String id, String name, String author, String desc) {

        this.id = id;
        this.name = name;
        this.author = author;
        this.desc = desc;
    }
    //getters and setters

我的 Controller :

public class TopicController {

    @Autowired
    private TopicService topicService;


    @RequestMapping(value = "/topics", method = RequestMethod.POST)
    public void addTopic(@RequestBody Topic topic) {
        topicService.addTopic(topic);
    }

我的服务:

@Service
public class TopicService {
    private List<Topic> topics = new ArrayList<>(Arrays.asList(
            new Topic("1", "topic1", "Martin", "T1"),
            new Topic("2", "topic2", "Jessie", "T2")  
            ));



    public void addTopic(Topic topic) {

        topics.add(topic);
    }

}

我的JSON:

{
    "id": "3",
    "name": "topic3",
    "author": "Jessie3",
    "desc": "T3"
}

请帮忙!

最佳答案

出于反序列化目的,主题 必须具有零参数构造函数。

例如:

public class Topic {
    private String id;
    private String name;
    private String author;
    private String desc;

    // for deserialisation
    public Topic() {}    

    public Topic(String id, String name, String author, String desc) {    
        this.id = id;
        this.name = name;
        this.author = author;
        this.desc = desc;
    }

    // getters and setters

}     

这是 Jackson 的默认行为图书馆。

关于java - JSON 解析错误 : Can not construct instance of io. starter.topic.Topic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448079/

相关文章:

spring-boot - 为什么 thymeleaf 消息显示不正确?

java - Junit 测试断言错误预期为 3,但结果为 0

java - 由于找不到 `HttpServletRequest` 类,@EnableZuulProxy 不起作用

Java编程任务效率

java - 打印格式化输出时的列间距问题

java - VS Code Java 调试器参数

java - Spring-Boot-Jersey 设置 CORS

java - 我可以在 Jxls 2+ 中的模板和输出格式中使用 .XLSX 吗?

java - Jersey 有没有办法从 URL 获取类

spring-boot - springboot找不到feignclient