0
votes

Please, I've a problem. I want to get all entities on web api(news.api)

But I've an execution error while retrofit response:

Error: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 57

Thanks for your help

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
What 's the actual JSON response? - ADM

1 Answers

1
votes

You got this exception because you are using List<String> source in your Post class means you want source as an array but in your JSON response it is an Object. so you have to change it to an object.

Make a class for your source object like the following.

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

And now You have to change source type in Post class like the following

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

Hope it helps you. Happy Coding