tux-world tux-world - 1 month ago 11
Android Question

Android Retrofit get array from web service

this below

jsonArray
is out result of web service:

{
"property":
{
"id": "2",
"title": "qqqqqqq",
"alias": "wwwwwwwww"
},
"foodList":
[
{
"meal": "1111",
"food": "1111111111"
},
{
"meal": "22222",
"food": "2222222222"
},
{
"meal": "3333333",
"food": "3333333333"
}
]
}


and i'm try to get and parse it, but i get this error:

Error

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 1 column 131 path $.foodList


class model like with result:

public class FoodLists {
private String userId;
private Property property;
private FoodList foodList;

public class Property {
private int id;
private String title;
private String alias;

/* Setter and Getters*/
}
public class FoodList {
private String meal;
private String food;

/* Setter and Getters*/
}

/* Setter and Getters*/
}


and my retrofit method to get that:

private void getUserFoodsLists() {
FoodLists getFoods = new FoodLists();
getFoods.setUserId("301323");
Call<FoodLists> call = behandamService.getFoodListsCall(getFoods);
call.enqueue(new Callback<FoodLists>() {
@Override
public void onResponse(Call<FoodLists> call, Response<FoodLists> response) {
if (response.isSuccessful()) {
}
}

@Override
public void onFailure(Call<FoodLists> call, Throwable t) {
Log.e("Err: ", t.getMessage());
}
});
}


how can i get this array with retrofit, Thanks in advance

Answer

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 131 path $.foodList

means that the response is returning a JsonArray but you told Gson to parse it as JsonObject. In your model class, change

 FoodList foodList;

with

 List<FoodList> foodList;
Comments