How to treat empty string as null using retrofit2 with Gson

时间:2019-04-16 22:34:21

标签: java json gson retrofit2 json-deserialization

I am using Retrofit2 with Gson to get a response from a public API.

The response looks something like this:

{"replies":[{"data":"value1"},{"data":"value2"}]}

but when the replies field is empty the data looks like this:

{"replies": ""}

So, if I treat replies like a string, I get an exception when I get an array. And when I treat it like an array I get an exception when I get an empty string.

Is there a way to resolve it so that I can ignore the value as if it is null when it is an empty string?

I would parse it manually but the actual response is huge and I would rather just use Gson than write a custom parse for the response.

1 个答案:

答案 0 :(得分:3)

You can write custom deserialiser which in case of JSON Array deserialise it using Gson base deserialiser and in all other cases you can return null or empty list. Take a look on below example:

class RepliesJsonDeserializer implements JsonDeserializer<List<Reply>> {

    @Override
    public List<Reply> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray()) {
            JsonArray array = json.getAsJsonArray();
            List<Reply> replies = new ArrayList<>(array.size());
            array.forEach(item -> replies.add(context.deserialize(item, Reply.class)));

            return replies;
        }

        // in all other case empty list or null
        return Collections.emptyList();
    }
}

I assume that your Pojo looks like below (Reply is a name of item class on the list):

class Replies {

    @JsonAdapter(RepliesJsonDeserializer.class)
    private List<Reply> replies;

    // getters, setters, toString
}

As you can notice we use @JsonAdapter annotation to register our RepliesJsonDeserializer custom implementation. I suggest to return Collections.emptyList() always just to have clear code and avoiding null-checking.