【问题标题】:Retrofit2: parse the part of dataRetrofit2:解析部分数据
【发布时间】:2016-04-07 15:12:13
【问题描述】:

我收到以下 json 响应:

{
     "error_code" : 0 ,
     "reason" : "success!" ,
     "result" : [
         {
             "id" : 1 ,
             "name" : "name1"
        } ,
         {
             "id" : 2 ,
             "name" : "name2"
        } ,
         {
             "id" : 3 ,
             "name" : "name3"
        } ,
         {
             "id" : 4 ,
             "name" : "name4"
        } ,
         {
             "id" : 5 ,
             "name" : "name5"
        } ,
         {
             "id" : 6 ,
             "name" : "name6"
        }
    ]
}

我只想解析部分数据。("result")

这是我的模型类:

public class ResultBean {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

还有APIService

public interface APIService {
    @GET("getCategory")
    Call<List<ResultBean>> getCategory(@Query("key") String key);
}

我知道修复模型类和完整解析,但我只想获取结果列表。

【问题讨论】:

    标签: json pojo retrofit2


    【解决方案1】:

    使用JsonElement作为响应类型并得到result数组作为响应:

    call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                if(response.isSuccessful()){
                    JsonElement jsonElement = response.body();
                    if(jsonElement.isJsonObject()){
                        JsonObject obj = jsonElement.getAsJsonObject();
                        // your array
                        JsonArray result = obj.getAsJsonArray("result");
                    } 
                   ...
    

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      相关资源
      最近更新 更多