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

Asked

Viewed 353 times

5

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

Follows the JSON:

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

My domain is mapped as follows, until the moment:

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

    }
}
  • Hello, would you be able to clarify a little more her?

  • 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.

1 answer

1

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.