我正在尝试使用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);
    }
}

最佳答案

据我所知,我已经成功建立了成功的联系


好吧,您将忽略此处的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());
    }
});


祝你好运!

09-10 22:03