Parse Dynamic Key Json String using Retrofit
Your resultInside
class is adding an extra object layer that does not exist in your JSON. Try moving the map to your Data
class results
field.
public class Data {
@SerializedName("results")
@Expose
private Map<String, Vitals> result;
//....
}
A better way to do this, would be:
----------------------
public class Report {
@SerializedName("data")
@Expose
private Data data;
----------------------
public class Data {
public HashMap<String, DataValues> dataValues;
public Data() {
this.dataVaues = new HashMap<>();
}
}
-----------------------------
then, create a Parser class like this:
public class DataParser implements JsonDeserializer<Data> {
@Override
public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Data result = new Data();
try {
final HashMap<String, DataValues> map = readServiceUrlMap(json.getAsJsonObject());
if(map != null) {
result.dataValues = map;
}
}catch (JsonSyntaxException ex){
return null;
}
return result;
}
private HashMap<String, DataValues> readServiceUrlMap(final JsonObject jsonObject) throws JsonSyntaxException {
if(jsonObject == null) {
return null;
}
Gson gson = new Gson();
HashMap<String, DataValues> products = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
DataValues value = gson.fromJson(entry.getValue(), DataValues.class);
products.put(key, value);
}
return products;
}
----------------------------------------------
after that, type this in your ApiClient class
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if(retrofit == null) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Data.class, new DataParser());
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.build();
I hope this will help someone