The simplest way is to declare the type that will receive the list as List<Map<String, String>>
. This is because GSon considers the "chave": "valor"
notation as an entry in a LinkedTreeMap .
public class Tipo{
@SerializedName("list")
private List<Map<String, String>> lista;
private int code;
private boolean success;
//getters
}
It will, however, be "more correct" to have one class, other than LinkedTreeMap , to represent each "chave": "valor"
value.
The way to do this is to use a custom deserializer .
First the class that will receive the result of deserialization:
public class Tipo{
@SerializedName("list")
private List<ListEntry> lista;
private int code;
private boolean success;
//getters
}
The content of the list, that is, each of the "chave": "valor"
values, will be represented by the ListEntry class:
class ListEntry {
private String key;
private String value;
public ListEntry(String key, String value) {
this.key = key;
this.value = value;
}
//getters
}
The custom deserializer :
private class ListEntryDeserializer implements JsonDeserializer<ListEntry> {
@Override
public ListEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Iterator<Map.Entry<String, JsonElement>> ite = json.getAsJsonObject().entrySet().iterator();
Map.Entry<String, JsonElement> entry = ite.next();
return new ListEntry(entry.getKey(), entry.getValue().getAsString());
}
}
Use this:
String jsonString = "{'list': [ {'1':'Bola' }, {'2': 'Quadrado' }, {'3': 'Retangulo' }], 'code': 0, 'success': true}";
Gson gson = new GsonBuilder().registerTypeAdapter(ListEntry.class, new ListEntryDeserializer()).create();
Tipo tipo = gson.fromJson(jsonString, Tipo.class);