0

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 $"

  • 1
    Might be these links will help you - https://stackoverflow.com/questions/40837031/how-to-fix-this-error-java-lang-illegalstateexception-expected-begin-array-but https://stackoverflow.com/questions/48296987/retrofit-expected-a-string-but-was-begin-object-at-line-1-column-2-path/48297208#48297208 – shridhar master May 11 '19 at 18:32

1 Answers1

1

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.

muetzenflo
  • 5,653
  • 4
  • 41
  • 82
  • With help of your comment, I change method to Call and now it goes into onResponse(), I still have few other problems but I resolved this one, thanks. – Patrick Jane May 11 '19 at 18:48