Retrofit: handle a property, which can be either an empty string or an array

I am using Retrofit2 and I was asked to use the following json:

{"status": "success", payload {"prop1": 1234, "prop2": ""}}

The problem is that prop2 can be an empty string or an array of objects. (An empty array is not an option for them)

I don’t remember that Retrofit has a mechanism to deal with this type of inconsistency. I am looking for a recipe to possibly get this property as a kind of universal object, perhaps to use it as an example, to analyze it, or some other alternative way to make it work.

+4
source share
1 answer

You can try this to check if prop2 is either an array or an empty string

JsonObject jsonObject = new Gson().fromJson("{ \"status\":\"success\", \"payload\": { \"prop1\": 1234, \"prop2\": \"\" } }", JsonObject.class);
JsonObject payload = jsonObject.getAsJsonObject("payload");
JsonElement jsonElement = payload.get("prop2");
if (jsonElement.isJsonArray()) {
    // value of prop2 is an array
} else if (jsonElement.isJsonPrimitive()) {
    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
    if (jsonPrimitive.isString() && "".equals(jsonPrimitive.getAsString())) {
        // value of prop2 is an empty String
    }
}
0
source

All Articles