【问题标题】:Android Retrofit - GET Json ArrayAndroid 改造 - 获取 Json 数组
【发布时间】:2020-05-14 20:24:01
【问题描述】:

当我在 onClick 侦听器中调用 getRetrofitArray() 函数以获取 JSon 数组时,我看到我的应用程序崩溃了。

我的代码如下,请帮助我:

  public void getRetrofitArray() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
    Call<BikeStation> call = service.getJsonArrayData();

    call.enqueue(new Callback<BikeStation>() {
        @Override
        public void onResponse(Call<BikeStation> call, Response<BikeStation> response) {
            Log.e("response ", response.body().toString());
            Log.e("number ", response.body().getNumber().toString());
            Log.e("address ", response.body().getAddress().toString());
            Log.e("name ", response.body().getName().toString());

            Log.e("banking ", response.body().getBanking().toString());
            Log.e("bonus ", response.body().getBonus().toString());
            Log.e("bike_stands ", response.body().getBike_stands().toString());
            Log.e("available_bike_stands ", response.body().getAvailable_bike_stands().toString());
            Log.e("available_bikes ", response.body().getAvailable_bikes().toString());
            Log.e("status ", response.body().getStatus().toString());
            Log.e("last_update ", response.body().getLast_update().toString());
        }

        @Override
        public void onFailure(Call<BikeStation> call, Throwable t) {

            Log.e("Error: ", t.toString());
        }
    });
}

我已经按照在线教程 (https://www.youtube.com/watch?time_continue=2&v=T-XFHVEdTUA&feature=emb_logo) 进行操作,但运气不佳。我无法在 logcat 上看到任何日志输出,除了

 java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

我使用的 JSON 数组具有以下结构:

[
{
"number": 42,
"contract_name": "dublin",
"name": "SMITHFIELD NORTH",
"address": "Smithfield North",
"position": {
  "lat": 53.349562,
  "lng": -6.278198
},
"banking": true,
"bonus": false,
"bike_stands": 30,
"available_bike_stands": 5,
"available_bikes": 25,
"status": "OPEN",
"last_update": 1589297754000
},
....

我相信这个问题与Gson issue:- Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 非常相似,但我看不出哪里出错了。请原谅我,

感谢您的热心帮助,

【问题讨论】:

标签: android json gson retrofit2


【解决方案1】:

来自 REST API 的响应是一个数组,但您传递了 BikeStation 作为预期的响应类型。尝试将其更改为Call&lt;List&lt;BikeStation&gt;&gt;,Callback&lt;List&lt;BikeStation&gt;&gt; 并更改getJsonArrayData() 中的返回类型。

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 2014-10-16
    • 2018-07-02
    • 2020-06-06
    • 2016-03-23
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2019-02-14
    相关资源
    最近更新 更多