0

Есть модель Message

@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
//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);
    }
}

Получаю ошибку

2016-11-06 10:52:53.857 WARN 1100 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : 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 instance of com.sttech.springrest.model.Message out of START_ARRAY token at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1]

Ответ от Postman

"exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "Could not read document: Can not deserialize 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 instance of com.sttech.springrest.model.Message out of START_ARRAY token\n at [Source: java.io.PushbackInputStream@6ccdce8a; line: 1, column: 1]"

Ну я так понял я получаю массив и его надо перевести в объект? Объясните на пальцах как.

2
  • что вы передаете в postman? 8 ноя 2016 в 6:40
  • Я передавал неправильный формат json [{}] вместо {}
    – Sergei R
    8 ноя 2016 в 7:15

1 ответ 1

0

Ошибка была в неправильной передачи Json данных. Я отсылал массив

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

а не одиночный элемент

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

Для массива используется конструкция

public ResponseEntity<?> addMessages(@RequestBody List<Message> newMessages) {

    return new ResponseEntity<Object>(messageRepository.save(newMessages), HttpStatus.CREATED);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.