首页 > 解决方案 > 如何使用 Retrofit 查询某些 JSON 项目?

问题描述

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

我设法JSON使用以下方法显示所有数据interface

@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 数据中,我该如何设置该接口?

提前感谢一堆:)

标签: javajsonandroid-studioretrofit2

解决方案


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

为了这:

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

并评论:

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

You cannot affect what the service returns but you can choose what you pick. Say you have this kind of DAO normally (the full Post -or is it Person?- data):

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

and normally you might have something like (not necessarli but as an example):

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

To restrict data to only some fields you can declare a new DAO for it. like:

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

and a new API method pointing the same endpoint:

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

But anyway you need to do the filtering on the client side.


推荐阅读