I am trying to fetch json object response using retrofit 2. I used hashmap as the keys are dynamic. Here is my response class :
public class Countries {
private Map<String, Model> datas;
public Map<String, Model> getDatas() {
return datas;
}
}
And the Model class is :
public class Model {
@SerializedName("country_name")
private String country_name;
@SerializedName("continent_name")
private String continent_name;
public String getCountry_name() {
return country_name;
}
public String getContinent_name() {
return continent_name;
}
}
So far, i've tried to handle the response like this :
call.enqueue(new Callback<Countries>() {
@Override
public void onResponse(Call<Countries> call, Response<Countries> response) {
Map<String, Model> map = new HashMap<String, Model>();
map = response.body().getDatas();
for (String keys: map.keySet()) {
// myCode;
}
}
@Override
public void onFailure(Call<Countries> call, Throwable t) {
}
});
And this error occurs :
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set java.util.Map.keySet()' on a null object reference
JSON response looks like this :
{
"0": {
"country_name": "Argentina",
"continent_name": "South America"
},
"1": {
"country_name": "Germany",
"continent_name": "Europe"
}
}
So how can I get the response in HashMap?