0
votes

This is my first time using jackson/consuming 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) . The api I'm trying to consume is 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();
    }

The api json format is https://pastebin.com/tbSaVJ1T

Here's my 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() +
            '}';
}

}

Data contains all the other classes/variables

1

1 Answers

0
votes

This is happening because you're trying to deserialize a Json Object into a List in java. 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.

Try changing:

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

into

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