Search code examples
javadeserializationhttpclienthttpresponseobjectmapper

how to handle two different types of response when consuming an API


I have to consume a REST API which can return two different types of responses. this is my code:

    HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());
    myObject = objectMapper.readValue(response.body.toString(),MyObject.class);

The problem is that I could receive MyObject or MyError as a response, how should I manage it?


Solution

  • You should look for the HTTP response code, and based on the code cast the response to the correct object.