Reputation: 11169
Hi I am new to the Retrofit 2.0 library, I am having problems parsing some json. I have looked at some other solutions on Stackoverflow but not having much luck with my problem. I am trying to call an api from android with retrofit 2.0.But it is throwing error Expected BEGIN_ARRAY but was BEGIN_OBJECT.
My response from web api is:
{
"items": [{
"id": 19,
"lat": 23.79418,
"lng": 90.401859,
"user_id": 1,
"created_at": null,
"updated_at": null,
"user": {
"id": 1,
"name": "Tarif",
"email": "[email protected]",
"created_at": null,
"updated_at": null
}
}]
}
This is how my Model class is:
public class UserResponse {
private List<Items> items;
public List<Items> getItems() {
return items;
}
private class Items{
private String id;
private String lat;
private String lng;
private String user_id;
private String created_at;
private String updated_at;
private List<User> user;
private class User{
private String id;
private String name;
private String email;
private String created_at;
private String updated_at;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCreated_at() {
return created_at;
}
public String getUpdated_at() {
return updated_at;
}
}
public String getId() {
return id;
}
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
public String getUser_id() {
return user_id;
}
public String getCreated_at() {
return created_at;
}
public String getUpdated_at() {
return updated_at;
}
public List<User> getUser() {
return user;
}
}
}
This is my interface:
@GET("coordinates")
Call <UserResponse> getUsers();
This is how I am calling:
ITCService service = ApiUtils.createService(ITCService.class);
Call<UserResponse> call= service.getUsers();
call.enqueue(new Callback<UserResponse>() {
@Override
public void onResponse(Call<UserResponse> call, retrofit2.Response<UserResponse> response) {
if (response.isSuccessful()) {
UserResponse res = response.body();
Log.e("TAG", res.toString());
} else {
// TODO: toast
Toast.makeText(getApplicationContext(),response.message(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UserResponse> call, Throwable t) {
// TODO: error alert
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
Upvotes: 2
Views: 189
Reputation: 3401
List<User>
should be HashMap<String,Object>
not a list because it is a JSONObject
not JSONArray
.Since you are defining User class in item itself just use User
instead of List.No need of HashMap
.
Upvotes: 1