'Parsing empty json array as null object with GSON

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_OBJECT but was BEGIN_ARRAY error when there is this kind of null response.



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hackbell
Solution 2 Umit Kose