Parsing dynamic Keys with GSON
If you want to parse some json response with dynamic keys and that too with GSON library, you can do that.
{ "1": [{ "id": "1", "name": "sample" }], "2": [{ "id": "2", "name": "sample2" }], "3": [{ "id": "3", "name": "sample3" }] }
1. All you need to do is to go through the available methods for parsing through gson of which there is one method with second param as Type of the Token. 2. You just need to identify your final object (either a json array or a json object). Also whether the final objects is assigned to a key or not
For above json, we can see that final response must go in an object but with the dynamic keys, it cannot be done through a defined modal implementation. So here what can be used for the dynamic keys is to get the details into a map of <String, Object to represent value> pair.
So final code for parsing here goes like this.
1. Define the modal class for json object representation at the lowest level
public class Stud {
@SerializedName("id") @Expose String id;
@SerializedName("name") @Expose String name;
}
2. Write the parsing code final with custom type token identification
Map<String, Collection<Stud>> parsedObject = new Gson().fromJson(jsonResponseString, new TypeToken<Map<String, Collection<Stud>>>() {}.getType()); That’s all.











