【问题标题】:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT Retrofitjava.lang.IllegalStateException:应为 BEGIN_ARRAY 但为 BEGIN_OBJECT 改造
【发布时间】:2020-02-03 13:30:08
【问题描述】:

拜托,我有问题。我想获取 web api 上的所有实体(news.api)

但我在retrofit 响应时出现执行错误:

错误:java.lang.IllegalStateException:应为 BEGIN_ARRAY,但在第 1 行第 57 列是 BEGIN_OBJECT

感谢您的帮助

public interface ApiService {

    @GET("top-headlines")
    Call<ResponseNewsApi> getResponseNewsApi(@Query("sources") String source, @Query("apiKey") String apiKey);

}

public class ResponseNewsApi {

    @SerializedName("status")
    private String status;
    @SerializedName("totalResults")
    private String totalResults;
    @SerializedName("articles")
    private List<Post> articles;
}

public class Post {

    @SerializedName("source")
    private List<String> source;

    @SerializedName("author")
    private String author;

    @SerializedName("title")
    private String title;

    @SerializedName("description")
    private String description;

    @SerializedName("url")
    private String url;

    @SerializedName("urlToImage")
    private String urlToImage;

    @SerializedName("publishedAt")
    private String publishedAt;

    @SerializedName("content")
    private String content;
}

service.getResponseNewsApi(source,apiKey).enqueue(new Callback<ResponseNewsApi>() {
            @Override
            public void onResponse(Call<ResponseNewsApi> call, Response<ResponseNewsApi> response) {
                Log.d(TAG, "onResponse response:: " + response);
                if (response.body() != null) {
                    data.setValue(response.body());
                    Log.d(TAG, "posts total result:: " + response.body().getTotalResults());
                    Log.d(TAG, "posts size:: " + response.body().getArticles().size());
                    Log.d(TAG, "posts title pos 0:: " + response.body().getArticles().get(0).getTitle());
                }
            }

            @Override
            public void onFailure(Call<ResponseNewsApi> call, Throwable t) {
                data.setValue(null);
                Log.e(TAG,"Error get enqueue Retrofit");
                Log.e(TAG,"Error: "+t.getMessage());
            }
        });
        return data;

【问题讨论】:

  • 实际的 JSON 响应是什么?

标签: java android retrofit illegalstateexception


【解决方案1】:

您遇到此异常是因为您在 Post 类中使用 List&lt;String&gt; source 意味着您希望将 source 作为 array 但在您的 JSON 响应中它是 Object。所以你必须把它改成object

为您的源对象创建一个类,如下所示。

 public class Source {
    private String id;
    private String name;
 }

现在你必须改变source 输入Post 类,如下所示

@SerializedName("source")
 //private List<String> source;
 private Source source; // source is an object in your response json

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2020-02-10
    • 2020-11-15
    • 2018-04-24
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多