How to get hashmap response using Retrofit 2
I am trying to get the response of a json object using modification 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 class Model
:
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 process a 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: Attempting to call interface method 'java.util.Set java.util.Map.keySet ()' on a null object reference
The 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 the HashMap?
source to share
The problem is what you are using Call<Countries>
when you should be using Call<Map<String, Model>>
. Your answer does not have a field named "data"; it's just a simple map object String
to Model
.
Remove the class Countries
and replace all references to it in the networking code with Map<String, Model>
.
source to share
Your method getDatas()
is retrieving null
because you haven't assigned data to it.
You have to do this to get the data:
map = response.body().datas;
Instead:
map = response.body().getDatas();
You should also replace this
private Map<String, Model> datas;
from
public Map<String, Model> datas;
Your code should look 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().datas;
for (String keys: map.keySet()) {
// myCode;
}
}
@Override
public void onFailure(Call<Countries> call, Throwable t) {
}
});
source to share