Reputation: 61
I made class Account which I annotated with @XMLRootElement, and I made a service class annotated with @Path("/") inside which in static block i made couple of Account objects and added them into List of type Account. In the same service, I made a method:
@GET
@Path("/accounts")
@Produces(MediaType.APPLICATION_JSON)
public List<Account> getAccounts(){
return accounts;
}
Since I'm running it on TomEE server, my complete URL is:
http://localhost:8080/android/accounts
Then I tested it with postman and got json objects alongside successful response.
In android, I made the same class (Account) with exact same fields. After that I made RestService interface:
public interface RestService {
@GET("accounts")
Call<List<Account>> getAccounts();
}
And in my main activity I'm trying to get data from server using retrofit2 library by making this method:
private void RetrofitAccounts(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.9:8080/android/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RestService restService = retrofit.create(RestService.class);
Call<List<Account>> call = restService.getAccounts();
call.enqueue(new Callback<List<Account>>() {
@Override
public void onResponse(Call<List<Account>> call, Response<List<Account>> response) {
Data.accounts = response.body();
//Data.accounts is my list of type Account
Log.i("SUCCESS","ACCOUNTS");
}
@Override
public void onFailure(Call<List<Account>> call, Throwable t) {
Log.i("FAILURE","ACCOUNTS");
t.printStackTrace();
}
});
}
When i start the app, it seems like it always goes into onFailure() method.
PrintStackTrace says "java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $"
Upvotes: 0
Views: 200
Reputation: 5682
The failure says that the json response starts with an object tag "{", but your model class expects a list tag "[".
My guess is that your server returns only 1 account while your response type for retrofit is defined as a list of accounts.
Upvotes: 1