预期是 BEGIN_ARRAY,但实际是 BEGIN_OBJECT,使用 Retrofit。

huangapple go评论80阅读模式
英文:

Expected BEGIN_ARRAY but was BEGIN_OBJECT with Retrofit

问题

以下是翻译好的内容:

我正试图从冠状病毒 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;
    }

    // Getters and Setters...
}

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

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) {
        // ... 做一些操作 ...
    }

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

然而,当我尝试启用调试器打开应用时,我只得到了“在第1行第2列路径$处预期为BEGIN_ARRAY,但实际为BEGIN_OBJECT”的错误。很明显,这是因为 JSON 不以县列表开头,然而我只想加载它们。我已尝试使用上述所示的 @Expose 标记,然而仍然无效。

非常感谢任何帮助 预期是 BEGIN_ARRAY,但实际是 BEGIN_OBJECT,使用 Retrofit。

英文:

So I am trying to load data from the corona api.

This is my interface:

public interface RKIApi {

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

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

This is my county data class to which I wish to convert the data I receive:

public class County {

@SerializedName(&quot;county&quot;)
@Expose
private String county;

@SerializedName(&quot;cases&quot;)
@Expose
private int cases;

@SerializedName(&quot;deaths&quot;)
@Expose
private int deaths;

@SerializedName(&quot;cases_per_population&quot;)
@Expose
private float casesPerPopulation;

@SerializedName(&quot;death_rate&quot;)
@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;
}

... Getters and Setters....

And this is how I am trying to load the data:

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

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

    Call&lt;List&lt;County&gt;&gt; call = apiService.getCounties();

    call.enqueue(new Callback&lt;List&lt;County&gt;&gt;() {
        @Override
        public void onResponse(@NonNull Call&lt;List&lt;County&gt;&gt; call,@NonNull Response&lt;List&lt;County&gt;&gt; response) {
            ... Do something ...
        }

        @Override
        public void onFailure(@NonNull Call&lt;List&lt;County&gt;&gt; call,@NonNull Throwable t) {
            System.out.println(&quot;========== ERROR ==========&quot;);
            System.out.println(t.getMessage());
        }
    });

However when I try to open the app with the debugger enabled all I get is Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $. Now this is obviously because the JSON doesn't start with the list of counties, I would however only like to load them. I have tried using the Expose Tag as seen above however its still not working.

Any help is very much appreciated 预期是 BEGIN_ARRAY,但实际是 BEGIN_OBJECT,使用 Retrofit。

答案1

得分: 1

这意味着您的任何参数为空值或在 JSON 中没有任何内容。假设您解析了 "name"= "pavel",但在 JSON 中它是 "name"=null。

英文:

This means any of your parameter getting null or don't have anything in the json. Suppose you parse "name"= "pavel" but in the json that is "name"=null

答案2

得分: 0

问题和错误的原因可能是由于糟糕设计的 API 或者误解的 API 导致的。您的 API 并没有发送对象列表。很可能 API 返回的 JSON 数据如下:

 { ...内容 }

这不是对象列表,而是单个对象。Retrofit 期望的数据格式如下:

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

因为您告诉 Retrofit 返回一个 List&lt;County&gt; 的列表。

其中 [ 表示对象数组。所以要修复这个问题,您有两个选择。要么更改 API,即使是空列表也始终返回方括号,像这样 [],或者对于单个结果返回 [ { 单个对象 } ]

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

当使用 Retrofit 时如何手动解析响应的部分内容

英文:

The problem and reason of the error is either in a bad designed API or in an misinterpreted api. Your api is not sending a List of objects.
Most probably the API is spitting a JSON like this:

 { ...content }

Which is not a list of objects but a Single object.
Retrofit is expecting something like this:

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

because You told to retrofit to return a LIST of List&lt;County&gt;.

Where the [ means an array of Objects.
So in order to fix this You have 2 choices. Either change the api so it will return always the square brackets even for empty List like this [] or this [{ one object }] for a single result.

Either parse Your results manually. Check please this question here on stackoverflow:

Manually parse part of a response when using Retrofit

huangapple
  • 本文由 发表于 2020年5月5日 01:29:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定