我试图从https://newsapi.org/v1/articles
的Retrofit获得JSON数据,但我是新手,迄今为止这一直很混乱。为什么我得到一个空对象?
从我可以告诉我,我已经设法建立一个成功的连接。但是,出于某种原因,我还无法确定,Retrofit不会将数据从JSON字符串映射到我的NewsAPI
类。
我会发布我目前正在使用的代码,我希望有人能帮我弄清楚这一点。谢谢!
Activity.java
:
final TextView tvTest = (TextView) findViewById(R.id.tvTest);
String url = "https://newsapi.org";
NewsAPI_Interface client = NewsAPI_Adapter.createService(NewsAPI_Interface.class);
Call<List<NewsAPI>> call = client.getData("techcrunch", "APIkeygoeshere");
call.enqueue(new Callback<List<NewsAPI>>() {
@Override
public void onResponse(Call<List<NewsAPI>> call, Response<List<NewsAPI>> response) {
if (response.body() != null) {
tvTest.setText(response.body().toString());
for (NewsAPI news: response.body()) {
System.out.println(news.source + " (" + news.status + ")");
tvTest.setText(news.source + " (" + news.status + ")");
}
} else {
tvTest.setText("It's null, " + response.errorBody().toString() + ", " + call.request().url());
}
}
@Override
public void onFailure(Call<List<NewsAPI>> call, Throwable t) {
tvTest.setText("An error ocurred!");
}
});
NewsAPI.java
:
public class NewsAPI {
String status;
String source;
public NewsAPI (String status, String source) {
this.status = status;
this.source = source;
}
}
NewsAPI_Interface.java
:
public interface NewsAPI_Interface {
@GET("/v1/articles")
Call<List<NewsAPI>> getData(@Query("source") String source, @Query("api_Key") String api_key);
}
NewsAPI_Adapter.java
:
public class NewsAPI_Adapter {
public static final String API_BASE_URL = "https://newsapi.org";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
如果我记得,您只能从'onResponse'方法中使用'response.body()' –
您使用的是proguard吗? –
另外,如果我阅读正确的话,'@Query(“api_Key”)'应该是'apiKey'。 https://newsapi.org/ –