java.lang.IllegalStateException:预期为 BEGIN_ARRAY

拜托,我有问题。我想获取 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;


慕少森
浏览 238回答 1
1回答

慕标5832272

List<String> source您得到此异常是因为您在类中使用 Post意味着您想要source作为 anarray但在您的JSON响应中它是一个Object。所以你必须将其更改为object.为源对象创建一个类,如下所示。&nbsp;public class Source {&nbsp; &nbsp; private String id;&nbsp; &nbsp; private String name;&nbsp;}现在你必须像下面这样改变类source中的类型Post@SerializedName("source")&nbsp;//private List<String> source;&nbsp;private Source source; // source is an object in your response json
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java