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

标签 java json android-studio retrofit2

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

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

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

RetrofitonResponse()方法中。但是,如果我只想显示 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,我该如何构建接口(interface)(收集名称或 ID)?缺少的参数是什么?

  3. 如何查询特定名称?比如我想查询JSON数据里有没有Bob,那个接口(interface)怎么设置?

提前致谢:)

最佳答案

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

为此:

  1. If I can query JSON directly, how do I structure the interface (to collect the names, or id)? And what's with the missing argument?

和评论:

So, there is no (good) way to take certain parts directly from the JSON data then?

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

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

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

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

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

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

和指向相同端点的新 API 方法:

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

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

关于java - 如何使用 Retrofit 查询某些 JSON 项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383084/

相关文章:

java - 找出构造了哪个枚举值

java - 带下划线的反斜杠 IntelliJ

java - 引发主逻辑循环中断

android - 原因:无效的类型代码:构建时为69 Android studio

android - Android Studio 中的 list 权限

java - String.format() 与字符串连接性能

php - 如何在android studio上使用webview获取json请求?

json - Sails Js-Waterline : Serialize, 解析并初始化模型

c# - 如何让 ASMX 文件输出 JSON

Android Studio 注释格式