本文介绍了JSON解析错误:无法构造io.starter.topic.Topic的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Spring Boot,我做了一个演示,但是当我发布添加对象的请求时,它不起作用!
Im learning Spring Boot and I made a demo but when I POST a request to add a Object it didn't work!
错误消息是:
{
"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
我的控制器:
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"
}
请帮助!
推荐答案
出于反序列化目的, Topic
必须具有零参数构造函数.
For deserialisation purposes Topic
must have a zero-arg constructor.
例如:
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 库的默认行为.
这篇关于JSON解析错误:无法构造io.starter.topic.Topic的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!