简体   繁体   中英

Java - httpclient consume restful api. Json api object contains Json arrays, can't parse with Jackson MismatchedInputException

This is the main api https://wallhaven.cc/help/api I'm not sure if the title explanation is correct, since I'm just started learning these topics.

If I try to consume this api https://wallhaven.cc/api/v1/w/pkgkkp it works because Data object only contains a single json array of objects.

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();

        WallHaven post = mapper.readValue(response.body(), new TypeReference<WallHaven>() {
        });
        System.out.println(post);

But, when I try to consume this api https://wallhaven.cc/api/v1/search?q=anime%20girls I get MismatchedInputException: Cannot deserialize value of type Data from Array value (token JsonToken.START_ARRAY )

Since it says the json starts with Array. Fine I'll try doing array instead

WallHaven[] posts = mapper.readValue(response.body(), WallHaven[].class);
        System.out.println(posts);

I get MismatchedInputException: Cannot deserialize value of type [LWallHaven; from Object value (token JsonToken.START_OBJECT )

so basically the problem is it askes for Object or Array. But, when I do the opposite it always ask for the other one.

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 data.getPath();
}

}

Data contains all the other json objects/arrays variable. I have no idea how to solve this problem.

You will have to make a new class WallHavenArray class. Create different Mapper class.One class will not work for both Apis as the structure of response is different

public class WallHavenArray {
public List<Data> data;

public WallHavenArray(List<Data> data) {
    this.data = data;
}


public WallHavenArray() {

}

@Override
public String toString() {
    return data; // Change this as well. Since now you have multiple Paths in single class
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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