Java 使用 httpclient 使用 restful api。遇到 Jackson json MismatchedInputException 问题

Java consuming restful api with httpclient. Having trouble with Jackson json MismatchedInputException

这是我第一次使用 jackson/consuming apis/httpclient。我收到此错误 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.ArrayList<WallHaven> from Object value (token JsonToken.START_OBJECT) 。我要消费的 api 是 https://wallhaven.cc/help/api

try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://wallhaven.cc/api/v1/w/pkgkkp"))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        ObjectMapper mapper = new ObjectMapper();
        List<WallHaven> posts = mapper.readValue(response.body(), new TypeReference<List<WallHaven>>() {
        });
        posts.forEach(System.out::println);


    } catch (Exception e) {
        e.printStackTrace();
    }

apijson格式为https://pastebin.com/tbSaVJ1T

这是我的 WallHaven class

public class WallHaven {
public Data data;

public WallHaven(Data data) {
    this.data = data;
}

public WallHaven() {

}

@Override
public String toString() {
    return "WallHaven{" +
            "data=" + data.getPath() +
            '}';
}

}

数据包含所有其他 classes/variables

发生这种情况是因为您试图将 Json Object 反序列化为 java 中的 List。错误消息解释说起始字符 (JsonToken.START_OBJECT) 是 json 对象的开始而不是 json 数组,因此您不能将其直接反序列化为 List,但应该将其反序列化为一个对象。

尝试更改:

List<WallHaven> posts = mapper.readValue(response.body(), new TypeReference<List<WallHaven>>())

进入

WallHaven post = mapper.readValue(response.body(), new TypeReference<WallHaven>())