首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改造2返回空体

改造2返回空体
EN

Stack Overflow用户
提问于 2017-10-20 20:45:20
回答 1查看 857关注 0票数 0

我正在尝试实现基本的练习改进:对github进行简单的get查询。我正在尝试获取一个存储库的列表,但是尽管结果的状态是200,但主体是空的。有一些关于github的票抱怨同样的问题,看起来它可能来自json转换器。我用的是gson。但我没发现哪个密码是罪魁祸首..。

下面是我的依赖关系:

代码语言:javascript
复制
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

存储库POJO:

代码语言:javascript
复制
public class Repository {
private int id;
private String name;
private String full_name;
private String html_url;

// getters + setters + toString

}

客户端接口:

代码语言:javascript
复制
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);

}

如何初始化:

代码语言:javascript
复制
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(GithubClient.ENDPOINT)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
githubClient = retrofit.create(GithubClient.class);

以及请求的执行:

代码语言:javascript
复制
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());
            }
        });
EN

回答 1

Stack Overflow用户

发布于 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",.}

在您的代码中,我看到了这个调用:

代码语言:javascript
复制
@GET("/search/repositories")
Call<List<Repository>> getByKeywords(@Query("q") String q);

如果收到的JSON响应结构如下:

代码语言:javascript
复制
[
  { "id": ... },
  { "id": ... }
]

换句话说,在真正的JSON响应中,"items"字段就是您所称的List<Repository>,但是您需要一些东西来表示顶级响应对象。

我会创建一个像这样的新类:

代码语言:javascript
复制
public class GithubResponse {

    private int total_count;
    private boolean incomplete_results;
    private List<Repository> items;
}

然后,我会将客户端接口中的调用更改为:

代码语言:javascript
复制
@GET("/search/repositories")
Call<GithubResponse> getByKeywords(@Query("q") String q);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46857067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档