need to get a Map from json, there is: json

 { "id":"1", "name":"aaa", "operations":[ { "type":"add", "value":"1" }, { "type":"delete", "value":"2" } ] } 

java

 public class User { private int id; private String name; private List<Operations> operations; public User(int id, String name, Operations operations) { this.id = id; this.name = name; this.operations = this.operations; } // geters and seters } public class Operations { private String type; private String value; public Operations(String type, String value) { this.type = type; this.value = value; } // geters and seters } 

gson

  // String userData = ... User user = gson.fromJson(userData, User.class); 

How to make in user instead of List was a Map and it was possible to get operations by key, for example user.getOperations.get("add");

    1 answer 1

    I see two options.

    The first one is to do it manually, like this:

     public class User { ... private List<Operations> operations; private Map<String, String> opMap; ... public Map<String, String> getOperations() { if (opMap == null) { //TODO создаём карту и перекладываем из списка } return opMap; } } 

    Second, replace the list with a card in User, add a custom deserializer for User:

     public class UserDeserializer implements JsonDeserializer<User> { @Override public User deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { User user = new User(); JsonObject ob = jsonElement.getAsJsonObject(); user.setId(ob.getAsJsonPrimitive("id").getAsInt()); user.setName(ob.getAsJsonPrimitive("name").getAsString()); Map<String, String> map = new HashMap<>(); JsonArray arr = ob.getAsJsonArray("operations"); for (JsonElement e: arr) { map.put(e.getAsJsonObject().getAsJsonPrimitive("type").getAsString(), e.getAsJsonObject().getAsJsonPrimitive("value").getAsString()); } user.setOperations(map); return user; } } 

    and then we deserialize it like this:

     Gson gson = new GsonBuilder() .registerTypeAdapter(User.class, new UserDeserializer()) .create(); User user = gson.fromJson(jsonString, User.class); 
    • Thank! everything worked out. - Dmitri88