簡體   English   中英

如何使用Retrofit 2解析嵌套對象?

[英]How do I parse nested objects with Retrofit 2?

我正在消費一個newsapi它的JSON響應與此相似。

{
"status": "ok",
"articles": [
    {
        "source": {
            "id": "bbc-news",
            "name": "BBC News"
        },
        "author": "BBC News",
        "title": "Jubilation greets end of Mugabe era",
        "description": "Zimbabweans celebrate late into the night after Robert Mugabe resigns, ending 37-year rule.",
        "url": "http://www.bbc.co.uk/news/world-africa-42072673",
        "urlToImage": "https://ichef.bbci.co.uk/images/ic/1024x576/p05nt3bn.jpg",
        "publishedAt": "2017-11-22T02:46:09Z"
    },
    {
        "source": {
            "id": "bbc-news",
            "name": "BBC News"
        },
        "author": "BBC News",
        "title": "Dramatic moment N Korea soldier defects",
        "description": "He raced across the border on foot, closely pursued by North Korean troops who shot at him several times.",
        "url": "http://www.bbc.co.uk/news/world-asia-42075986",
        "urlToImage": "https://ichef.bbci.co.uk/news/1024/cpsprodpb/F519/production/_98854726_p05ntph4.jpg",
        "publishedAt": "2017-11-22T04:45:14Z"
    },
    {
      ....
    }
  ]
}

我正在嘗試將Retrofit 2與GSON配合使用。

我的POJO類是這些。

新聞列表.java

public class NewsList {
  public Articles[] articles;
  private String status;

  @Override
  public String toString() {
    return "ClassPojo [articles = " + articles + ", status = " + status + "]";
  }

  // getters and setters
}

Articles.java

public class Articles {
  private String publishedAt;
  private String author;
  private String urlToImage;
  private String title;
  private Source source;
  private String description;
  private String url;

 // getters and setters
}

源代碼

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

  // getters and setters
}

我的翻新客戶看起來像這樣;

public interface NewsroomAPI {
  String BASE_URL = "https://newsapi.org/v2/";

  @GET("top-headlines")
  Call<NewsList> loadNews(@Query("sources") String source);

}

在我的MainActivity.java我這樣調用Retrofit客戶端;

OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
    @Override public okhttp3.Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request.Builder builder = originalRequest.newBuilder().header("Authorization",
                getString(R.string.newsroom_api_key));
        Request newRequest = builder.build();
        return chain.proceed(newRequest);
    }
}).build();

Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(NewsroomAPI.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.client(okHttpClient).build();
    NewsroomAPI getNewsAPI = retrofit.create(NewsroomAPI.class);

    Call<NewsList> call = getNewsAPI.loadNews("bbc-news");
    call.enqueue(new Callback<NewsList>() {
        @Override public void onResponse(Call<NewsList> call, Response<NewsList> response) {
            if (response.isSuccessful()) {
                NewsList newslist = response.body();
                Log.w(TAG, "Articles result: " + newslist);
            } else {
                Toast.makeText(getContext(), "Some error occurred while fetching results!",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override public void onFailure(Call<NewsList> call, Throwable t) {
            Log.w(TAG, "Failed! ", t);
        }
    });

當我運行活動並記錄結果時,問題就來了。 我希望看到status和返回的articles的日志。 但是,狀態已成功返回,但是articles對象為null 輸出看起來像這樣;

 W/GlobalNewsFragment: Articles result: ClassPojo [articles = null, status = ok]

問題似乎來自Retrofit2反序列化返回的JSON對象的方式。 我做錯了什么嗎?

這些是我的build.gradle文件中的依賴

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile "com.android.support:recyclerview-v7:26.1.0"
compile "com.squareup.okhttp3:okhttp:3.8.0"

您的POJO類應如下所示。

public class Article {

@SerializedName("source")
@Expose
private Source source;
@SerializedName("author")
@Expose
private String author;
@SerializedName("title")
@Expose
private String title;
@SerializedName("description")
@Expose
private String description;
@SerializedName("url")
@Expose
private String url;
@SerializedName("urlToImage")
@Expose
private String urlToImage;
@SerializedName("publishedAt")
@Expose
private String publishedAt;
// your getter setter methods
}

您的NewsList POJO如下所示。

public class NewsList {

@SerializedName("status")
@Expose
private String status;
@SerializedName("articles")
@Expose
private List<Article> articles = null;
// getter setter
}

而您的source POJO如下所示。

public class Source {

@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
// getters setters 
}

AFAIK Gson將JsonArray反序列化為List 嘗試這個:

public class NewsList {
  public List<Articles> articles;
  private String status;

  //some code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM