繁体   English   中英

如何使用 Retrofit 查询某些 JSON 项目?

[英]How do I query certain JSON items using Retrofit?

我正在使用Retrofit收集和解析我创建并上传到互联网的JSON数据。 我可以成功显示所有数据,但我是 Retrofit 的新手,我很难理解如何从JSON数据中查询和显示某些项目。

我设法使用interface显示所有JSON数据:

@GET("d6jww")
Call<List<RetrofitVariables>> findPosts();

onResponse()的方法Retrofit 但是,如果我只想显示JSON对象的名称或 id,该怎么办。 我如何查询?

我试过:

@GET("d6jww")
Call<List<RetrofitVariables>> getId(
        @Query( "id" )
                String id);

和:

@GET("d6jww")
Call<List<RetrofitVariables>> getId(
        @Query("SELECT * FROM id")
                String id);

但是在我的ViewModel Android-Studio想让我在使用interface时添加一个参数,老实说我不知道​​如何使用它:

public Call<List<RetrofitVariables>> getRepositoryId() {
    return this.repository.getRetrofitRepository().getId( ??? );
}

我的JSON如下所示:

[
    {"id":231, "name": "Bob", "date":"3/13/2015",     
    "from":"8:00","until":"13:00"},

    {"id":232, "name": "Joe", "date":"1/3/2015",   
    "from":"12.30","until":"13:00"}
]

总结我的问题:

  1. 我可以直接查询JSON还是首先需要将其放入Room并从那里查询?

  2. 如果我可以直接查询JSON ,我该如何构建接口(收集名称或 ID)? 缺少的参数是什么?

  3. 如何查询特定名称? 例如,如果我想查询Bob是否在JSON数据中,我该如何设置那个接口?

提前感谢一堆:)

这不是你想要做的,但无论如何。

为了这:

  1. 如果我可以直接查询 JSON,我该如何构建接口(收集名称或 ID)? 缺少的参数是什么?

并评论:

那么,没有(好的)方法可以直接从 JSON 数据中获取某些部分吗?

您不能影响服务返回的内容,但您可以选择您选择的内容。 假设您通常拥有这种 DAO(完整的 Post - 或者是 Person?- 数据):

public class Post {
    private String id;
    private String name;
    private String date;
    private String from;
    private String until;
}

通常你可能有类似的东西(不是 necessarli 但作为一个例子):

@GET("d6jww")
Call<List<Post>> findPosts();

要将数据限制为仅某些字段,您可以为其声明一个新的 DAO。 喜欢:

@Getter @Setter
public class PostId {
    private String id;
}

以及指向同一端点的新 API 方法:

@GET("d6jww")
Call<List<PostId>> getPostIds();

但无论如何,您需要在客户端进行过滤。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM