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.