The simplest way is to declare the type that will receive the list as List<Map<String, String>>
. This is because the Gson considers the rating "chave": "valor"
as an input into 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, another that Linkedtreemap, to represent each value "chave": "valor"
.
The way to achieve this is to resort to a custom deserializer.
First the class that will receive the result of the 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 values "chave": "valor"
, will be represented by the class Listentry:
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 like 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);
Hello, would you be able to clarify a little more her?
– Carlos Bridi
Use your online tool http://cleancss.com/json-editor/ or http://jsonlint.com/ are very useful, if you do not find the key, its structure is this
[ ]
is key.– KingRider