我制作了训练REST服务,现在我尝试添加新项目。
模型消息:
@Entity
@Table(name="message")
public class Message{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "MESSAGE")
private String message;
@Column(name = "AUTHOR")
private String author;
@Column(name = "CREATED")
@Temporal(TemporalType.DATE)
private Date created;
public Message() {}
public Message(Long id, String message, String author) {
this.id = id;
this.message = message;
this.author = author;
this.created = new Date();
}
+ getters / setters
MessageController:
@RestController
public class MessageController {
@Autowired
private MessageRepository messageRepository;
@RequestMapping(
value = "/api/messages",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addMessage(@RequestBody Message newMessage) {
return new ResponseEntity<>(messageRepository.save(newMessage), HttpStatus.CREATED);
}
}
错误:
2016-11-06 10:52:53.857 WARN 1100 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver:无法读取HTTP 信息: org.springframework.http.converter.HttpMessageNotReadableException: 无法读取文档:无法反序列化实例 com.sttech.springrest.model.Message退出START_ARRAY令牌 [来源:java.io.PushbackInputStream@6ccdce8a; line:1,column:1]; 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:不能 反序列化com.sttech.springrest.model.Message的实例 START_ARRAY令牌位于[来源:java.io.PushbackInputStream@6ccdce8a; line:1,column:1]
通过邮递员我在json中发送新数据并获得邮递员答案
[
{
"message": "Hello World1",
"author": "ABC"
}
]
“异常”: “org.springframework.http.converter.HttpMessageNotReadableException” “message”:“无法读取文档:无法反序列化实例 com.sttech.springrest.model.Message out of START_ARRAY token \ n at [来源:java.io.PushbackInputStream@6ccdce8a; line:1,column:1]; 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:不能 反序列化com.sttech.springrest.model.Message的实例 START_ARRAY令牌\ n在[来源:java.io.PushbackInputStream@6ccdce8a; line:1,column:1]“
如何解决?我认为这个模型不会被识别。
答案 0 :(得分:4)
您的服务需要一条消息。但是,您发送一组消息(尽管它只包含一条消息)。
所以而不是:
[
{
"message": "Hello World1",
"author": "ABC"
}
]
你应该发送:
{
"message": "Hello World1",
"author": "ABC"
}