java - 无法从 api 获得响应
问题描述
我有 API 新闻 它由元素 web 名称、密钥、国家/地区组成 一切都很好,我首先测试了链接: https ://newsapi.org/v2/top-headlines?country=eg&apiKey= e80f949de1a34b94804188af28f08f44 然后我构建了所需的类,并设置一个接口并放入 Headers , Query ,当我调用它时,我发现了一个错误。
///
public class RetrofitClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://newsapi.org/";
public static Retrofit getRetrofitInstance(){
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
///-----
public interface GetData {
String API_KEY="e80f949de1a34b94804188af28f08f44";
@Headers("X-Api-Key:"+API_KEY)
@GET("/v2/top-headlines")
Call<List<Response>>getAllHeadlines(@Query("country") String country);
}
//- MainActivity
GetData service = RetrofitClient.getRetrofitInstance().create(GetData.class);
Call<List<Response>> call = service.getAllHeadlines("eg");
call.enqueue(new Callback<List<Response>>(){
@Override
public void onResponse(Call<List<Response>> call, retrofit2.Response<List<Response>> response) {
Log.d("print","Don"+response.body());
}
@Override
public void onFailure(Call<List<Response>> call, Throwable t) {
Log.d("print","nON"+t.getMessage());
}
});
// Log.d
D/print: nONExpected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
解决方案
这与 Gson 转换器有关。您期待一个 List 但 json 在开始时返回一个 json 对象而不是一个 json 数组。检查您的模型,以便您可以根据 json 更改它。
推荐阅读
- python-3.x - TKINTER:如何从列表框中删除项目/将项目添加到列表框中
- sql - 从 1 个表中选择条件在另一个表中的情况?
- javascript - 如何阻止我的 JavaScript 给出
- javascript - 当我尝试将电子商务应用程序上传到 Heroku 时出现 redux 记录器错误
- string - 无法更改 dtype pandas python
- c# - 复制后删除目录 XCOPY
- swift - 人们如何处理迭代 Swift 结构值类型属性?
- amazon-web-services - 使用具有指定存储类的 boto3 生成签名的 S3 url
- python - Python函数中多个输出的括号
- mysql - 当价值超过平均值时如何计算