【问题标题】:Receiving error "Expected BEGIN_ARRAY but was BEGIN_OBJECT" [duplicate]接收错误“预期为 BEGIN_ARRAY,但为 BEGIN_OBJECT”[重复]
【发布时间】:2017-09-15 21:13:41
【问题描述】:

我有这个问题,似乎无法找到解决方案。我用 Google 搜索了一遍,但无济于事。

API 正在返回一个对象数组,但 gson 找到了一个对象。

我的模型

public class Message {

private int id;
private String title;
private String details;  }

消息客户端

public interface MessageClient {

@GET("/api/test")
Call<List<Message>> getMessages();}

实施

Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();

MessageClient client =  retrofit.create(MessageClient.class);
Call<List<Message>> call = client.getMessages();

call.enqueue(new Callback<List<Message>>() {
    @Override
    public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
        List<Message> messageList = response.body();
        Log.d(TAG, "LIST: "+messageList);
    }

    @Override
    public void onFailure(Call<List<Message>> call, Throwable t) {
        Log.d(TAG, "API ERROR: "+t.getMessage());
    }
});

来自 API 的样本数据

[
{
    "id": 1,
    "title": "Title 1",
    "details": "Message1.",
    "client_id": 1,

},
{
    "id": 2,
    "title": "Title 2",
    "details": "Message 2.",
    "client_id": 1,
}]

我在哪里错过它?请注意 API 示例数据。

【问题讨论】:

  • 您遇到了什么问题?
  • 您能否更清楚地说明实际问题?
  • 另外,请注意,Retrofit 的最新版本使记录原始 HTTP 对话变得非常容易。
  • 我收到此错误应为 BEGIN_ARRAY 但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT
  • 请使用这些详细信息更新问题(另外,您在哪里看到此错误,以及何时?)。无论如何,你给它一个对象,而不是一个数组。见:stackoverflow.com/q/36177629/1531971

标签: android gson retrofit


【解决方案1】:

是的,API 不是返回一条消息,而是返回一组消息。因此,您需要将其映射为列表,而不是单个消息。

所以我建议: 1. 您创建一个额外的模型、bean 或 pojo。 你可以叫它MessageList,它看起来像:

public class MessagesList {
  private List<Message> messageList;
//add getters and setters .. etc.
}
  1. 我认为您还应该将代码中的 List&lt;Message&gt; 更改为 MessageList

这应该允许将 API 返回的消息列表映射到 MessageList 模型,每个单独的消息将映射到带有其(唯一?)id、标题和详细信息的 Message 对象。现在您可以遍历列表以获取每个 Message

祝你好运

【讨论】:

  • 感谢您的建议。但我意识到代码没有问题,只是我使用了错误的 API url。
猜你喜欢
  • 2019-03-04
  • 2017-05-16
  • 2020-07-26
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 2015-11-26
  • 2018-03-27
相关资源
最近更新 更多