Retrofit2 Android: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ Retrofit2 Android: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ android android

Retrofit2 Android: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $


When you say "This code is working with this payload:... but not with this one:..." that's expected and that's how it's suppose to work. In fact the error message tells you that while converting the json to a java object the call expected an array in the json but got an object instead.

This call:

@GET("Music")Call<List<Music>> getMusicList();

expects a list of Music objects, that's why it works with the json:

[  {    "login": "JakeWharton",    ...  },  ...]

Because the json itself is an array of your Music objects (Retrofit can convert between json arrays to java lists). For the second json you have just an object and not an array (notice the lack of [...]). For this you need to create another call with another model that maps to that json. Let's assume you've named the model MusicList. Here's how the call could look like:

@GET("Music")Call<MusicList> getMusicList();

(Note that you might need to change the method name if you want to keep both the first call and this one).

The MusicList model can look something like this:

public class MusicList {  @SerializedName("data")  private List<Music> musics;  // ...}

I'm assuming that the data array is a list of Music objects, but I did notice that the jsons are completely different. You might need to adapt this as well, but I think you get the picture here.


I meet with this problem. Because playload is object instead of object array. So I remove List.

Code Example

UserAPI.java

public interface UserAPI {    @GET("login/cellphone")    Call<LoginResponse> login(@Query("phone") String phone,                               @Query("password") String password);}

Call code

Retrofit retrofit = new Retrofit        .Builder()        .addConverterFactory(GsonConverterFactory.create())        .baseUrl(Constant.CLOUD_MUSIC_API_BASE_URL)        .build();UserAPI userAPI = retrofit.create(UserAPI.class);userAPI.login(phone, password).enqueue(new Callback<LoginResponse>() {    @Override    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {        System.out.println("onResponse");        System.out.println(response.body().toString());    }    @Override    public void onFailure(Call<LoginResponse> call, Throwable t) {        System.out.println("onFailure");        System.out.println(t.fillInStackTrace());    }});