我正在使用 Retrofit
来收集和解析我创建并上传到互联网的 JSON
数据。我可以成功显示所有数据,但作为 Retrofit 的新手,我很难理解如何从 JSON
数据中查询和显示某些项目。
我设法使用 interface
显示所有 JSON
数据:
@GET("d6jww")
Call<List<RetrofitVariables>> findPosts();
在Retrofit
的onResponse()
方法中。但是,如果我只想显示 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"}
]
总结一下我的问题:
我可以直接查询
JSON
还是需要先将它放在Room
中然后从那里查询?如果我可以直接查询
JSON
,我该如何构建接口(interface)(收集名称或 ID)?缺少的参数是什么?如何查询特定名称?比如我想查询JSON数据里有没有Bob,那个接口(interface)怎么设置?
提前致谢:)
最佳答案
这不是您想做的,但无论如何。
为此:
- 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/