为什么我得到一个空对象?

时间:2016-10-10 20:26:25

标签: java android json retrofit retrofit2

我正试图通过Retrofit从https://newsapi.org/v1/articles获取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);
    }
}

1 个答案:

答案 0 :(得分:1)

  

据我所知,我已成功建立了连接

好吧,你在这里忽略了Throwable,你输出错误的地方。

@Override
public void onFailure(Call<List<NewsAPI>> call, Throwable t) {
    tvTest.setText("An error ocurred!");
}

您期待的回答看起来像这样

{
    "status": "ok",
    "source": "techcrunch",
    ...

{开始一个对象,而不是List,因此,您应该以不同方式定义您的界面。然后文档说API密钥已添加到带有apiKey的URL,因此请更改它。

public interface NewsAPI_Interface {
    @GET("/v1/articles")
    Call<NewsAPI> getData(@Query("source") String source, @Query("apiKey") String api_key);
}

(你需要为Article类定义另一个对象。但这是一个Gson问题,而不是Retrofit)

最后,我记得在某个地方读过response.body()应该只调用一次。

Call<NewsAPI> call = client.getData("techcrunch", "APIkeygoeshere");

call.enqueue(new Callback<NewsAPI>() {
    @Override
    public void onResponse(Call<List<NewsAPI>> call, Response<List<NewsAPI>> response) {
        final NewsAPI responseBody = response.body();
        if (responseBody != null) {
            tvTest.setText(responseBody.toString());

            String news = news.source + " (" + news.status + ")";
            Log.i("responseBody", news);
            tvTest.setText(news);

        } 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!");
        Log.e("news Error", t.getMessage());
    }
});

祝你好运!