拜托,我有問題。我想獲取 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;
1 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
List<String> source您得到此異常是因為您在類中使用 Post意味著您想要source作為 anarray但在您的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
添加回答
舉報
0/150
提交
取消