0

I'm using a web service to do some tasks. I have a problem in parsing the response of one of the APIs provided, which gives response as like below in different cases. The response code is 200 for both the cases.

  • A String(Not a JSON), when there are no records found in their database or invalid API version passed in the request URL.
  • A JSON, when the response is success(that is, in most of the cases)

So, I have gone with the below approach to fix this parsing issue. My doubt is, using Optional in this case, is right option or not?

// inside json parse utlity method
try {
    // success
    return Optional.of(objectMapper.readValue(responseBody, MyObject.class));
} catch(JsonParseException e) {
    // when the response is not JSON. That is a `String`
    return Optional.empty();
} catch(Exception e) {
    throw new RuntimeException(e);
}

// do other stuff if value is present in Optional, otherwise skip

I'm using jackson library and Spring Boot REST service. If there is a better approach, please help me with that.

the_tech_maddy
  • 575
  • 2
  • 6
  • 21
  • Offhand it seems very strange for an API to return JSON or non-JSON to the same call - are you sure that there is nothing else to distinguish? eg, I would hope that the response code is different to indicate the error - eg returns 200 (HttpStatus.OK) for the JSON, something else for the error message. – racraman Jul 16 '19 at 02:23
  • See for example: https://stackoverflow.com/questions/23205213/how-to-extract-http-status-code-from-the-resttemplate-call-to-a-url – racraman Jul 16 '19 at 02:32
  • I also thought of extracting response code. But sadly, they are giving response code as 200 for both the scenarios and sorry for not mentioning this earlier in the question. – the_tech_maddy Jul 16 '19 at 03:55
  • I have never seen such a poor API design and I have no chance of using other/similar APIs – the_tech_maddy Jul 16 '19 at 04:18
  • 1
    Wow, that’s horrible, and you have my sympathies ! Go with your best shot in that case, and the above is fine. My only concern being if the message might become important (eg, I can imagine callers wanting to be informed that they’re using an outdated version) - but that’s just me not knowing your environment :) – racraman Jul 16 '19 at 04:43

0 Answers0