Android中Retrofit调用API无响应问题求助
Hey there, it's totally normal to hit this kind of snag when you're just starting out with Retrofit—let's break down what's going wrong and fix it step by step.
The Core Issue
Your API returns a top-level JSON object that wraps the posts array (which contains your articles), but you're trying to directly map the entire response to a List<Article>. Retrofit can't automatically convert that nested structure into a list, so it's failing to parse the data properly.
Step 1: Create a Top-Level Response Class
First, we need a class to represent the full JSON structure your API sends back. Let's call it NewsResponse:
public class NewsResponse { @SerializedName("status") @Expose private String status; @SerializedName("count") @Expose private Integer count; @SerializedName("count_total") @Expose private Integer countTotal; @SerializedName("pages") @Expose private Integer pages; @SerializedName("posts") @Expose private List<Article> posts; // Getters and Setters public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Integer getCountTotal() { return countTotal; } public void setCountTotal(Integer countTotal) { this.countTotal = countTotal; } public Integer getPages() { return pages; } public void setPages(Integer pages) { this.pages = pages; } public List<Article> getPosts() { return posts; } public void setPosts(List<Article> posts) { this.posts = posts; } }
Step 2: Fix Your Retrofit Interface
Update your NewsService to return a Call<NewsResponse> instead of Call<List<Article>>:
public interface NewsService { @GET("your-api-endpoint-here") // Replace with your actual API path Call<NewsResponse> getNewestArticles(); }
Step 3: Update the Retrofit Call Code
Adjust your enqueue logic to handle the new response type, and extract the posts array correctly:
NewsService service = RetrofitClient.getRetrofitInstance().create(NewsService.class); Call<NewsResponse> call = service.getNewestArticles(); call.enqueue(new Callback<NewsResponse>() { @Override public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) { dialog.dismiss(); if (response.isSuccessful() && response.body() != null) { // Extract the articles list from the top-level response List<Article> articles = response.body().getPosts(); generateDataList(articles); } else { // Log errors for debugging if the response isn't successful Log.e("Retrofit", "Failed to get data: Response code " + response.code()); } } @Override public void onFailure(Call<NewsResponse> call, Throwable t) { dialog.dismiss(); // Always log failure details—this is critical for debugging! Log.e("Retrofit Error", t.getMessage(), t); // You can also show an error message to the user here } });
Step 4: Clean Up Your Article Class
Looking at your JSON, the status field exists at the top level (not inside each post). You accidentally added it to your Article class—remove those lines to avoid parsing errors:
// Delete these lines from Article.java: // @SerializedName("status") // @Expose // private String status; // public String getStatus() { return status; } // public void setStatus(String status) { this.status = status; }
Quick Sanity Checks
Make sure these are in place too:
- Your
RetrofitClientincludesGsonConverterFactory(required for JSON parsing):Retrofit retrofit = new Retrofit.Builder() .baseUrl("your-base-api-url") .addConverterFactory(GsonConverterFactory.create()) .build(); - You've added the internet permission in
AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" />
Why This Works
By creating the NewsResponse class, we're telling Retrofit exactly how to map the full JSON structure. We then extract the posts array from that response and pass it to your generateDataList method—this matches what your API actually sends back.
内容的提问来源于stack exchange,提问作者venura

