当前位置: 首页 > 知识库问答 >
问题:

java.lang.IllegalStateException:应为BEGIN_ARRAY,但为BEGIN_OBJECT改型

席言
2023-03-14

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

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;

共有1个答案

贾俊喆
2023-03-14

出现此异常是因为您在post类中使用了list source 这意味着您希望source作为数组但在JSON响应中它是对象。因此必须将其更改为对象

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

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

现在您必须更改post类中的source类型,如下所示

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

希望对你有帮助。快乐编码

 类似资料: