繁体   English   中英

Java 使用 httpclient 消耗宁静的 api。 Jackson json MismatchedInputException 出现问题

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

这是我第一次使用jackson/消费apis/httpclient。 I'm getting this error 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();
    }

api json 格式为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() +
            '}';
}

}

数据包含所有其他类/变量

发生这种情况是因为您试图将 Json Object反序列化为 java 中的List The error message explains it by saying that the starting character ( JsonToken.START_OBJECT ) is the start of a json object not a json array, so you can't deserialize it directly into a List , but should deserialize it into an object.

尝试改变:

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

进入

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM