java - 使用 Gson Response.body() 进行改造不起作用

标签 java android json gson retrofit

我正在尝试将数据解析到回收器 View ,我遇到了一些关于期望 JSONArray/JSONObject 的问题,我在一些帮助下修复了这些问题,但此时我有点迷失在 Onresponse< 中该做什么,原来的 - generatePhonesList(response.body()) 不起作用。

这是我的 json,我正在尝试解析 array results[] 中的数据:

{
  "success": true,
  "metadata": {
    "sort": "POPULARITY",
    "total_products": 20,
    "title": "Phones & Tablets",
    "results": [
      {
        "sku": "1",
        "name": "Samsung Galaxy S9",
        "brand": "Samsung",
        "max_saving_percentage": 30,
        "price": 53996,
        "special_price": 37990,
        "image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
        "rating_average": 5
      },

MainActivity(CALL 和 Recyclerview 创建):

    GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);

        Call<APIReponse> call = service.getAllPhones();

       call.enqueue(new Callback<APIReponse>() {
           @Override
           public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
              generatePhonesList(response.body());


           }

           @Override
           public void onFailure(Call<APIReponse> call, Throwable t) {
                Log.e("eee" , "" + t.getMessage());
           }
       });

    }

    private void generatePhonesList(List<Result> phonesList){
        recyclerView = findViewById(R.id.recyclerView);
        adapter = new PhonesAdapter(phonesList,this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

这是在 jsonschema2pojo 中创建的 POJO 类:

public class APIReponse {

    @SerializedName("success")
    @Expose
    private Boolean success;
    @SerializedName("metadata")
    @Expose
    private Metadata metadata;

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public Metadata getMetadata() {
        return metadata;
    }

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

}

2级

public class MetaData {
    @SerializedName("sort")
    @Expose
    private String sort;
    @SerializedName("total_products")
    @Expose
    private Integer totalProducts;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("results")
    @Expose
    private List<Result> results = null;

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public Integer getTotalProducts() {
        return totalProducts;
    }

    public void setTotalProducts(Integer totalProducts) {
        this.totalProducts = totalProducts;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Result> getResults() {
        return results;
    }

    public void setResults(List<Result> results) {
        this.results = results;
    }
}

3 类:


public class Result {

    @SerializedName("sku")
    @Expose
    private String sku;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("brand")
    @Expose
    private String brand;
    @SerializedName("max_saving_percentage")
    @Expose
    private Integer maxSavingPercentage;
    @SerializedName("price")
    @Expose
    private Integer price;
    @SerializedName("special_price")
    @Expose
    private Integer specialPrice;
    @SerializedName("image")
    @Expose
    private String image;
    @SerializedName("rating_average")
    @Expose
    private Integer ratingAverage;

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public String getName() {
        return name;
    }

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

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getMaxSavingPercentage() {
        return maxSavingPercentage;
    }

    public void setMaxSavingPercentage(Integer maxSavingPercentage) {
        this.maxSavingPercentage = maxSavingPercentage;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getSpecialPrice() {
        return specialPrice;
    }

    public void setSpecialPrice(Integer specialPrice) {
        this.specialPrice = specialPrice;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Integer getRatingAverage() {
        return ratingAverage;
    }

    public void setRatingAverage(Integer ratingAverage) {
        this.ratingAverage = ratingAverage;
    }
}

最佳答案

您正在传递APIReponse型号为generatePhonesList(List<Result> phonesList)功能。您只需在此函数中传递结果列表。

替换这个:

generatePhonesList(response.body());

与:

generatePhonesList(response.body().getMetadata().getResults());

这里的getMetadata()和getResults()是元数据模型和List的getter函数。

关于java - 使用 Gson Response.body() 进行改造不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59397345/

相关文章:

javascript - 如何修复无限滚动表?

java - 多播客户端如何从发送方接收单独的拷贝?

java - 如何让 Android 旋转器处于 Activity 状态?

android - 因为来自 sdk 的 flutter_test 的每个版本都依赖于路径 1.8.1,而 easy_localization 3.0.0 依赖于路径 >=1.8.0-nullsafety

javascript - 通过javascript获取移动设备硬件信息

android - 在 Android 中将替代短信发送器设置为默认发送器

java - 为什么我用 while( in.hasNext() ) 从键盘获取值

java - 在 Java/Android 中解析多个 JSON 数组

c# - 来自 SelectionChanged 事件 WinRT 的 ArgumentOutOfRangeException

javascript - 将数组对象添加到对象中