【问题标题】:Can not deserialize instance of model.* out of START_ARRAY token\n at无法反序列化模型实例。* 超出 START_ARRAY 令牌\n at
【发布时间】:2017-03-20 14:06:48
【问题描述】:

我制作了培训 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

消息控制器:

@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 警告 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;行:1,列:1]; 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:不能 反序列化 com.sttech.springrest.model.Message 的实例 [来源:java.io.PushbackInputStream@6ccdce8a 处的 START_ARRAY 令牌; 行:1,列:1]

通过 Postman,我以 json 格式发送新数据并获得 Postman 答复

[
  {
    "message": "Hello World1",
    "author": "ABC"
  }
]

“例外”: "org.springframework.http.converter.HttpMessageNotReadableException", “消息”:“无法读取文档:无法反序列化 com.sttech.springrest.model.Message out of START_ARRAY token\n at [来源:java.io.PushbackInputStream@6ccdce8a;行:1,列:1]; 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:不能 反序列化 com.sttech.springrest.model.Message 的实例 [来源:java.io.PushbackInputStream@6ccdce8a; 的 START_ARRAY 令牌\n; 行:1,列:1]"

如何解决?我认为模型没有得到 id。

【问题讨论】:

    标签: json rest spring-boot


    【解决方案1】:

    您的服务需要一条消息。但是,您发送了一组消息(尽管它只包含一条消息)。

    所以而不是:

    [
      {
        "message": "Hello World1",
        "author": "ABC"
      }
    ]
    

    你应该发送:

    {
      "message": "Hello World1",
      "author": "ABC"
    }
    

    【讨论】:

    • 如何发送数组?
    • 您的意思是:如何处理 JSON 数组?您需要将 API 的签名更改为public ResponseEntity&lt;?&gt; addMessage(@RequestBody List&lt;Message&gt; newMessages),然后处理消息列表。
    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2020-07-14
    • 2020-09-23
    相关资源
    最近更新 更多