I am working with some not really well designed APIs and when the object is null it returns empty array, like this:
No-null response:
"SourceType": {
"ID": "2",
"NameCZ": "Pokyny",
"NameEN": "Information"
},
Null response:
"SourceType": [],
Is there a way to parse the null response as null object with GSON? Because when I try to simple parse it to POJO it obviously throws Expected BEGIN_ARRAY but was BEGIN_OBJECT
error when there is this kind of null response.
CodePudding user response:
As far as I know there isn't. I think you should ask them to change the service structure. If you want, you can compare the http service response code returned in an empty state with the http service response code returned in a full state. if this is different, you can parse accordingly.
CodePudding user response:
Try to use Optionals to avoid null values for example
Optional<SourceType> response;
Then you can use
response.isPresent();
More info: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html