java - 如何使用 Retrofit 2 解析嵌套对象?

标签 java android gson retrofit2

我正在使用一个 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 类是这些;

NewsList.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
}

Source.java

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);
        }
    });

当我运行 Activity 并记录结果时,问题就出现了。 我期望包含 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
}

您的 POJO 如下所示。

public class Source {

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

关于java - 如何使用 Retrofit 2 解析嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434338/

相关文章:

java - 如何创建生成随机数数组列表的方法

java - 如何在 Java 中解析 HTTP 请求?

android - 警报设置后立即显示警报通知,即使时间是 future 时间

android - 分页库在加载初始数据时不会触发观察

android - 如何使标题在对话框中居中?

java - Gson:将 MySQL 日期时间反序列化为 Java 对象

java - Retrofit & Gson - 防止 gson 将 Long 转换为科学记数法

android - Gson 发布方法

java - 如何使用 Java 8 在与 ifPresent 相同的条件下返回 orElseThrow?

java - @Sql 失败的 SQL 脚本 : The configured DataSource [*] (named 'fooDS' ) is not the one associated with transaction manager [*] (named 'fooTM' )