There is a Message model

@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 Controller

 @RestController //http://localhost:8080/api/messages 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); } } 

I get an error

2016-11-06 10: 52: 53.857 WARN 1100 --- [nio-8080-exec-1] .wsmsDefaultHandlerExceptionResolver: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of com.sttech.springrest.model.Message out of START_ARRAY token at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize the instance of com.sttech.springrest.model.Message out of START_ARRAY token at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1]

Postman response

"exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "Could not read the document: Can not deserialize the instance of com.sttech.springrest.model.Message out of START_ARRAY token \ n at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize the instance of com.sttech.springrest.model.Message out of START_ARRAY token \ n at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1] "

Well, as I understand it, I get an array and need to translate it into an object? Explain on the fingers how.

  • What do you transfer to postman? - Sergii Getman Nov
  • I passed the wrong format json [{ }] instead of { } - Sergei R

1 answer 1

The error was in the wrong transfer of Json data. I sent an array

 [ { "message": "Hello World 11", "author": "ABC", "created": "" } ] 

rather than a single item

 { "message": "Hello World 11", "author": "ABC", "created": "" } 

For an array, the construction is used

 public ResponseEntity<?> addMessages(@RequestBody List<Message> newMessages) { return new ResponseEntity<Object>(messageRepository.save(newMessages), HttpStatus.CREATED); }