How to deserialize a list with items of type {"key": "value"}?

5

I need to deserialize a JSON, but I can not map the enumerated object.

Follow JSON:

{
  "list": [
    {
      "1": "Bola"
    },
    {
      "2": "Quadrado"
    },
    {
      "3": "Retangulo"
    }
  ],
  "code": 0,
  "success": true
}

My domain is mapped as follows, so far:

public class Objeto {

    @SerializedName(value="list")
    public List<objClass> objList;

    public void setObj(List<objClass> month) {
        this.objList = month;
    }

    public class objClass {

        //Aqui eu deveria mapear o objeto com a cheve numerica

    }
}
    
asked by anonymous 11.08.2016 / 01:08

1 answer

1

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);
    
11.08.2016 / 17:54