LEE
LEE

Reputation: 3605

Retrofit 1.9 - Same variable name, different JSON type - CONVERSION exception

I have a JSON key called buttons This JSON key can take either forms, a JSON Array OR a JSON Object. However, since I'm using Pojos, I can define only one type of buttons variable. Either Buttons buttons (for JSON object) or List<Buttons> buttons (for JSON Array). But this causes retrofit's CONVERSION exception if the run time type of buttons does not match my variable type. What should be my approach to this situation? Can Retrofit 2 solve this problem?

Code :

When buttons is of type JSON array

buttons: [
{
title: "key1",
value: "value1"
},
{
title: "key2",
value: "value2"
},
{
title: "key3",
value: "value3"
}
],

When buttons is of type JSON object

buttons: {
title: "key",
value: "value"
},

Upvotes: 1

Views: 293

Answers (1)

Vitaliy Shuba
Vitaliy Shuba

Reputation: 41

In this situation better solution to create JsonDeserializer

You can use something like this:

public class TestDeser implements JsonDeserializer<ButtonList>{
@Override
public ButtonList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final ButtonList list = new ButtonList();
    if (json.isJsonArray()) {
        for (int i = 0; i < json.getAsJsonArray().size(); i++) {
            final Button btn = context.deserialize(json.getAsJsonArray().get(i), Button.class);
            list.buttons.add(btn);
        }
    } else {
        final Button btn = context.deserialize(json.getAsJsonObject(), Button.class);
        list.buttons.add(btn);
    }
    return list;
}}

In this example you can see how to check input json is it JsonArray or JsonObject and proceed with default logic of parsing Button.

You can register this deserializer as follows below:

new GsonBuilder().registerTypeAdapter(ButtonList.class, new TestDeser()).create();

Upvotes: 1

Related Questions