【问题标题】:Expected BEGIN_ARRAY but was BEGIN_OBJECT with Retrofit预期为 BEGIN_ARRAY,但为 BEGIN_OBJECT 与改造
【发布时间】:2020-05-05 06:31:24
【问题描述】:

所以我正在尝试从 corona api 加载数据。

这是我的界面:

public interface RKIApi {

String BASE_URL = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/";

@Headers("Content-Type: application/json")
@GET("query?where=1%3D1&outFields=cases,deaths,cases_per_population,county,death_rate&returnGeometry=false&outSR=4326&f=json")
Call<List<County>> getCounties();
}

这是我希望将收到的数据转换为的县数据类:

public class County {

@SerializedName("county")
@Expose
private String county;

@SerializedName("cases")
@Expose
private int cases;

@SerializedName("deaths")
@Expose
private int deaths;

@SerializedName("cases_per_population")
@Expose
private float casesPerPopulation;

@SerializedName("death_rate")
@Expose
private float deathRate;

public County(String county, int cases, int deaths, float casesPerPopulation, float deathRate) {
    this.county = county;
    this.cases = cases;
    this.deaths = deaths;
    this.casesPerPopulation = casesPerPopulation;
    this.deathRate = deathRate;
}

... Getter 和 Setter....

这就是我尝试加载数据的方式:

Retrofit retrofit = new Retrofit.Builder().baseUrl(RKIApi.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RKIApi apiService = retrofit.create(RKIApi.class);

    Call<List<County>> call = apiService.getCounties();

    call.enqueue(new Callback<List<County>>() {
        @Override
        public void onResponse(@NonNull Call<List<County>> call,@NonNull Response<List<County>> response) {
            ... Do something ...
        }

        @Override
        public void onFailure(@NonNull Call<List<County>> call,@NonNull Throwable t) {
            System.out.println("========== ERROR ==========");
            System.out.println(t.getMessage());
        }
    });

但是,当我尝试在启用调试器的情况下打开应用程序时,我得到的只是预期的 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处是 BEGIN_OBJECT。现在这显然是因为 JSON 不以县列表开头,但我只想加载它们。我已尝试使用如上所示的 Expose Tag,但它仍然无法正常工作。

非常感谢任何帮助:)

【问题讨论】:

    标签: java android api retrofit


    【解决方案1】:

    这意味着您的任何参数变为 null 或 json 中没有任何内容。假设您解析 "name"= "pavel" 但在 json 中是 "name"=null

    【讨论】:

      【解决方案2】:

      错误的问题和原因在于设计不良的 API 或被误解的 API。您的 api 未发送对象列表。 API 很可能会像这样吐出 JSON:

       { ...content }
      

      这不是对象列表,而是单个对象。 改造期待这样的事情:

       [ { ....County } { ..County  }? ]
      

      因为您告诉改造返回List&lt;County&gt; 的列表。

      [ 表示对象数组。 所以为了解决这个问题,你有 2 个选择。要么更改 api,因此即使对于像 [] 这样的空列表,它也将始终返回方括号,或者对于单个结果,这样的 [{ one object }]

      要么手动解析您的结果。请在stackoverflow上检查这个问题:

      Manually parse part of a response when using Retrofit

      【讨论】:

        猜你喜欢
        • 2015-07-24
        • 2014-08-01
        • 2015-11-26
        • 2018-03-27
        • 2016-06-28
        • 2019-02-06
        • 1970-01-01
        • 2019-03-04
        • 2017-05-16
        相关资源
        最近更新 更多