-2

Main method

public static void apiRequest(String country){
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://covid-19-data.p.rapidapi.com/report/country/name?date=2020-04-01&name="+country))
            .header("x-rapidapi-host", "covid-19-data.p.rapidapi.com")
            .header("x-rapidapi-key", "e7d0ae3dfcmshb4765a4bcd9edc9p198994jsn1a1b1d5fa50d")
            .method("GET", HttpRequest.BodyPublishers.noBody())
            .build();
    HttpResponse<String> response = null;
    try {
        response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(response.body());

    ObjectMapper oM = new ObjectMapper();

    oM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {
        Covid covid = oM.readValue(response.body(), Covid.class);
        System.out.println(covid);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

Here the whole response String: [{"country":"Austria","provinces":[{"province":"Austria","confirmed":10711,"recovered":1436,"deaths":146,"active":9129}],"latitude":47.516231,"longitude":14.550072,"date":"2020-04-01"}]

I only want certain values from the Covid class

Covid class

public class Covid {
String province;
int active;

public Covid(String province, int active) {
    this.province = province;
    this.active = active;
}

public String getProvince() {
    return province;
}

public void setProvince(String province) {
    this.province = province;
}

public int getActive() {
    return active;
}

public void setActive(int active) {
    this.active = active;
}
}

My error: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type Covid from Array value (token JsonToken.START_ARRAY)

Please help me

Goggi
  • 32
  • 8

1 Answers1

-1

The API result is an array, and you are trying to read a single object value. Make sure to read a collection or an array when calling oM.readValue

coladict
  • 4,799
  • 1
  • 16
  • 27