I know this is not the first time someone asking about this problem but with Retrofit2 I can't find the right solution to my problem. I followed a online tutorial and it worked just fine. When I applied same code to my own endpoint i get this exception: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ I don't know how to solve this.

接口:

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();
}

Client code:

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

}

推荐答案

当你说"这段代码正在处理这个负载:……但不是处理这个负载:…"这是意料之中的,这就是它的工作原理.事实上,错误消息告诉您,在将json转换为java对象时,调用期望json中有一个数组,但得到了一个对象.

This call:

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

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

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

因为json本身是Music个对象的数组(Retrofit可以在json数组到java列表之间转换).对于第二个json,您只有一个对象,而不是数组(请注意,缺少[...]).为此,您需要使用映射到该json的另一个模型创建另一个调用.让我们假设您已将模型命名为MusicList.下面是呼叫可能的形式:

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

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

MusicList型号可能看起来像这样:

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

我假设data数组是Music个对象的列表,但我注意到JSON是完全不同的.你可能也需要调整一下,但我想你明白了.

Json相关问答推荐

使用jq解析多层json

Jolt转换问题—使用键查找匹配对象

如何使用ChoETL将复杂的JSON转换为CSV

Flutter -控制器问题-JSON API

无法从MongoDB集合中检索正确的文档

将部分数据字节解组到自定义 struct 中

nlohmann json:为什么我会得到一个解析错误?

错误:在 NX 工作区中找不到模块../swagger.json

NoneType 对象的 Python 类型错误

使用 Powershell,如何将 Azure AD 组成员转换为 Json 对象(文件),然后可以更新?

如何在 jq 中按 IP 地址排序?

使用 serde 和 csv crates 将嵌套的 json 对象序列化为 csv

如何将复杂的 JSON 反序列化为 Rust 类型?

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

嵌套 JSON 到 CSV(多级)

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

JSON 到 JSON 转换器

在视图中将 .Net 对象转换为 JSON 对象

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

春天:返回@ResponseBodyResponseEntity>