How to handle parameters that can be ARRAY or OBJECT in Retrofit on Android?

I am having a problem where the API handler I'm processing returns an OBJECT for an ARRAY of size 1.

For example, sometimes the API responds:

{
    "monument": [
        {
            "key": 4152,
            "name": "MTS - Corporate Head Office",
            "categories": {},
            "address": {}
        },
        {
            "key": 4151,
            "name": "Canadian Transportation Agency",
            "categories": {},
            "address": {}
        },
        {
            "key": 4153,
            "name": "Bank of Montreal Building",
            "categories": {},
            "address": {}
        }
    ],
}

However, if the array monumenthas only 1 element, it becomes an OBJECT (note the absence of brackets []) like this:

{
    "monument": {
        "key": 4152,
        "name": "MTS - Corporate Head Office",
        "categories": {},
        "address": {}
    }
}

If I define my models as follows, I get an error when only one element is returned:

public class Locations {
    public List<Monument> monument;
}

If only one element is returned, I get the following error:

Expected BEGIN_OBJECT but was BEGIN_ARRAY ...

And if I define my model as follows:

public class Locations {
    public Monument monument;
}

and the API returns ARRAY. I get the opposite error.

Expected BEGIN_ARRAY  but was BEGIN_OBJECT ...

I cannot define multiple elements with the same name in my model. How can I handle this case?

. API.

+14
3

, TypeAdapter.

public class LocationsTypeAdapter extends TypeAdapter<Locations> {

    private Gson gson = new Gson();

    @Override
    public void write(JsonWriter jsonWriter, Locations locations) throws IOException {
        gson.toJson(locations, Locations.class, jsonWriter);
    }

    @Override
    public Locations read(JsonReader jsonReader) throws IOException {
        Locations locations;

        jsonReader.beginObject();
        jsonReader.nextName();       

        if (jsonReader.peek() == JsonToken.BEGIN_ARRAY) {
            locations = new Locations((Monument[]) gson.fromJson(jsonReader, Monument[].class));
        } else if(jsonReader.peek() == JsonToken.BEGIN_OBJECT) {
            locations = new Locations((Monument) gson.fromJson(jsonReader, Monument.class));
        } else {
            throw new JsonParseException("Unexpected token " + jsonReader.peek());
        }

        jsonReader.endObject();
        return locations;
    }
}
+11

Gson Locations. , . :

public class LocationsDeserializer implements JsonDeserializer<Locations> {

    @Override
    public Locations deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        JsonElement monumentElement = json.getAsJsonObject().get("monument");
        if (monumentElement.isJsonArray()) {
            return new Locations((Monument[]) context.deserialize(monumentElement.getAsJsonArray(), Monument[].class));
        } else if (monumentElement.isJsonObject()) {
            return new Locations((Monument) context.deserialize(monumentElement.getAsJsonObject(), Monument.class));
        } else {
            throw new JsonParseException("Unsupported type of monument element");
        }
    }
}

vararg Locations:

public class Locations {
    public List<Monument> monuments;

    public Locations(Monument ... ms) {
        monuments = Arrays.asList(ms);
    }
}

. - :

public class Monument {
    public int key;
    public String name;
    // public Categories categories;
    // public Address address;
}

, Gson RestAdapter.

Gson gson = new GsonBuilder().registerTypeAdapter(Locations.class, new LocationsDeserializer()).create();

RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(baseUrl)
            .setConverter(new GsonConverter(gson))
            .build();
+10

You can register TypeAdapterwith Gson, which conditionally handles this behavior.

You will call first peekToken(). If he was BEGIN_ARRAY, then just deserialize how List<Foo>. If it is BEGIN_OBJECT, then deserialize as you Foowrap in Collections.singletonList.

Now you always have a list, be it one item or many.

0
source

All Articles