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?
The problem is that you're using Call<Countries>
when you should be using Call<Map<String, Model>>
. Your response has no field named "datas"; it's just a plain map of String
to Model
objects.
Delete the Countries
class and replace all references to it in your networking code with Map<String, Model>
.
Your method getDatas()
retruns null
because you did not assign the data to it.
You should do it this way to get the data:
map = response.body().datas;
Instead of:
map = response.body().getDatas();
You should also replace this
private Map<String, Model> datas;
with
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) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With