Skip to content Skip to sidebar Skip to footer

Retrofit2: Convert Json With Dynamic Keys To A Map With Model Also Containing Those Keys

I'm using Retrofit 2 in combination with Gson and RxJava. My JSON data looks something like this: { 'groups': { '1': { 'name': 'First group',

Solution 1:

Step A - Create a group class:

publicclassGroup {
    String name;
    Stringtype;
}

Step B - Create a groups class:

publicclassGroups {
    List<Group> userList;
}

Step C - Create a GSON Deserializer class

publicclassMyDeserializerimplementsJsonDeserializer<Groups> {
    privatefinalStringgroups_key="groups";

    @Overridepublic Groups deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)throws JsonParseException {
        Groupsgroups=newGroups();
        JsonObjectobject= json.getAsJsonObject().getAsJsonObject(groups_key);
        Map<String, Group> retMap = newGson().fromJson(object, newTypeToken<HashMap<String, Group>>() {}.getType());

        List<Group> list = newArrayList<Group>(retMap.values());
        groups.userList = list;

        return groups;
    }
}

Step D - Register your Deserializer when you create your Gson object

Gson gson = newGsonBuilder()
                        .registerTypeAdapter(Groups.class, newMyDeserializer()).create();

Step E - Convert your JSON object via. Gson

Groupsgroups= gson.fromJson(jsonExmple, Groups.class);

Notes:

  • When your JSON object gets bigger you can expand your Group/Groups classes and add more variables. Keep in mind that you will need to reflect everything in your Deserializer class. :)
  • Use @SerializedName annotation when your variable got a different name from your JSON key

Post a Comment for "Retrofit2: Convert Json With Dynamic Keys To A Map With Model Also Containing Those Keys"