Java-Retrofit2 Android:应为BEGIN_ARRAY,但位于第1行第2列路径的BEGIN_OBJECT $

我知道这不是第一次有人问这个问题,但是有了Retrofit2,我找不到合适的解决方案。 我遵循了在线教程,效果很好。 当我将相同的代码应用于自己的端点时,出现以下异常:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $我不知道该如何解决。

接口:

public interface MyApiService {

// Is this right place to add these headers?
@Headers({"application-id: MY-APPLICATION-ID",
        "secret-key: MY-SECRET-KEY",
        "application-type: REST"})
@GET("Music")
Call<List<Music>> getMusicList();



Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(MySettings.REST_END_POINT)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
}

客户代码:

MyApiService service = MyApiService.retrofit.create(MyApiService.class);
Call<List<Music>> call = service.getMusicList();
call.enqueue(new Callback<List<Music>>() {

    @Override
    public void onResponse(Call<List<Music>> call, Response<List<Music>> response) {
        Log.e("MainActivity", response.body().
    }

    @Override
    public void onFailure(Call<List<Music>> call, Throwable t) {
        Log.e("MainActivity", t.toString());
    }
});

此代码与此有效负载一起使用:

[
{
    "login": "JakeWharton",
    "id": 66577,
    "avatar_url": "https://avatars.githubusercontent.com/u/66577?v=3",
    "gravatar_id": "",
    "url": "https://api.github.com/users/JakeWharton",
    "html_url": "https://github.com/JakeWharton",
    "followers_url": "https://api.github.com/users/JakeWharton/followers",
    "following_url": "https://api.github.com/users/JakeWharton/following{/other_user}",
    "gists_url": "https://api.github.com/users/JakeWharton/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/JakeWharton/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/JakeWharton/subscriptions",
    "organizations_url": "https://api.github.com/users/JakeWharton/orgs",
    "repos_url": "https://api.github.com/users/JakeWharton/repos",
    "events_url": "https://api.github.com/users/JakeWharton/events{/privacy}",
    "received_events_url": "https://api.github.com/users/JakeWharton/received_events",
    "type": "User",
    "site_admin": false,
    "contributions": 741
},
{....

但与此不:

{
"offset": 0,
"data": [
    {
        "filename": "E743_1458662837071.mp3",
        "created": 1458662854000,
        "publicUrl": "https://api.backendless.com/dbb77803-1ab8-b994-ffd8-65470fa62b00/v1/files/music/E743_1458662837071.mp3",
        "___class": "Music",
        "description": "",
        "likeCount": 0,
        "title": "hej Susanne. ",
        "ownerId": "E743756F-E114-6892-FFE9-BCC8C072E800",
        "updated": null,
        "objectId": "DDD8CB3D-ED66-0D6F-FFA5-B14543ABC800",
        "__meta": "{\"relationRemovalIds\":{},\"selectedProperties\":[\"filename\",\"created\",\"publicUrl\",\"___class\",\"description\",\"likeCount\",\"title\",\"ownerId\",\"updated\",\"objectId\"],\"relatedObjects\":{}}"
    },
    {...

我的音乐课:

public class Music {

   private String ownerId;
   private String filename;
   private String title;
   private String description;
   private String publicUrl;
   private int likeCount;

   // Getters & Setters

}
oxyt asked 2020-01-14T11:39:51Z
2个解决方案
97 votes

当您说“此代码正在使用此有效负载:...而不是与此:: ...”时,这是预期的,这就是假定的工作方式。 实际上,错误消息告诉您,在将json转换为java对象时,该调用期望在json中使用数组,但得到了一个对象。

这个电话:

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

需要一个Music对象的列表,这就是为什么它可以与json一起工作的原因:

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

因为json本身是data对象的数组(Retrofit可以在json数组与Java列表之间进行转换)。 对于第二个json,您只有一个对象而不是一个数组(请注意缺少Music)。 为此,您需要使用映射到该json的另一个模型创建另一个调用。 假设您已将模型命名为MusicList。这是调用的样子:

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

(请注意,如果要同时保留第一个调用和该调用,则可能需要更改方法名称)。

data模型可以如下所示:

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

我假设data数组是Music对象的列表,但我确实注意到json完全不同。 您可能还需要对此进行调整,但是我认为您可以在此处找到所需的图片。

Fred answered 2020-01-14T11:40:43Z
2 votes

我遇到这个问题。 因为playload是对象而不是对象数组。 所以我删除列表。

代码示例

UserAPI.java

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

通话代码

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());
    }
});
shellhub answered 2020-01-14T11:41:16Z
translate from https://stackoverflow.com:/questions/36177629/retrofit2-android-expected-begin-array-but-was-begin-object-at-line-1-column-2