我正在尝试实现基本的练习改进:对github进行简单的get查询。我正在尝试获取一个存储库的列表,但是尽管结果的状态是200,但主体是空的。有一些关于github的票抱怨同样的问题,看起来它可能来自json转换器。我用的是gson。但我没发现哪个密码是罪魁祸首..。
下面是我的依赖关系:
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'存储库POJO:
public class Repository {
private int id;
private String name;
private String full_name;
private String html_url;
// getters + setters + toString}
客户端接口:
public interface GithubClient {
public static final String ENDPOINT = "https://api.github.com";
@GET("/users/{user}/repos")
Call<List<Repository>> getByUser(@Path("user") String user);
@GET("/search/repositories")
Call<List<Repository>> getByKeywords(@Query("q") String q);}
如何初始化:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GithubClient.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
githubClient = retrofit.create(GithubClient.class);以及请求的执行:
Call<List<Repository>> request = githubClient.getByUser(inputText);
request.enqueue(new Callback<List<Repository>>() {
@Override
public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
progress.setVisibility(View.GONE);
results.setText(response.toString());
}
@Override
public void onFailure(Call<List<Repository>> call, Throwable t) {
progress.setVisibility(View.GONE);
results.setText(t.getMessage());
}
});发布于 2017-10-20 23:45:58
我在浏览器中访问了https://api.github.com/search/repositories?q=threetenabp,并看到了与您预期的不同的JSON结构:
{ "total_count":4,"incomplete_results":false,"items":{ "id":38503932,"name":"ThreeTenABP",},{ "id":61799973,"name":"ThreeTenABPSample",. },{ "id":78114982,"name":"TwitterPack",},{ "id":76958361,"name":"ZonedDateTimeProguardBug",.}
在您的代码中,我看到了这个调用:
@GET("/search/repositories")
Call<List<Repository>> getByKeywords(@Query("q") String q);如果收到的JSON响应结构如下:
[
{ "id": ... },
{ "id": ... }
]换句话说,在真正的JSON响应中,"items"字段就是您所称的List<Repository>,但是您需要一些东西来表示顶级响应对象。
我会创建一个像这样的新类:
public class GithubResponse {
private int total_count;
private boolean incomplete_results;
private List<Repository> items;
}然后,我会将客户端接口中的调用更改为:
@GET("/search/repositories")
Call<GithubResponse> getByKeywords(@Query("q") String q);https://stackoverflow.com/questions/46857067
复制相似问题