com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法从 START_ARRAY 令牌中反序列化 `Todo` 的实例

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `Todo` out of START_ARRAY token

我有这个 json,我将其转换为 POJO

将JSON转换为POJO文件

[
    {
        "postId": 81,
        "id": 401,
        "name": "cum voluptate sint voluptas veritatis",
        "email": "Vella.Mayer@colten.net",
        "body": "sit delectus recusandae qui\net cupiditate sed ipsum culpa et fugiat ab\nillo dignissimos quo est repellat dolorum neque\nvoluptates sed sapiente ab aut rerum enim sint voluptatum"
    },
    {
        "postId": 81,
        "id": 403,
        "name": "cum voluptate sint voluptas veritatis",
        "email": "Vella.Mayer@colten.net",
        "body": "sit delectus recusandae qui\net cupiditate sed ipsum culpa et fugiat ab\nillo dignissimos quo est repellat dolorum neque\nvoluptates sed sapiente ab aut rerum enim sint voluptatum"
    }
]

这是POJOclass我把它转换成了

public class TodoItem{
    private int id;
    private boolean completed;
    private String title;
    private int userId;

我尝试使用 todo 来验证 class 类型的响应,但总是出现此错误。

Todo todo = response.getBody().as(Todo.class);
Assert.assertTrue(response.statusCode() == 200);

错误

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `io.christdoes.pojo.todo.Todo` out of START_ARRAY token
 at [Source: (String)"[

你做错了两件事:

  • 您正在匹配的 POJO
  • 映射方式(数组不能映射到一个对象)

会是

List<TodoItem> todoItems = response.as(new TypeRef<>() {});

POJO(我用lombok生成getters/setters)

import lombok.Data;

@Data
public class TodoItem{
    private int postId;
    private int id;
    private String name;
    private String email;
    private String body;
}