我知道这不是第一次有人问这个问题,但是有了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}",
呼唤远方