使用Retrofit在recyclerview适配器中访问嵌套的JSON数据

时间:2018-12-09 17:06:19

标签: java android json android-recyclerview retrofit2

我正在使用Retrofit2.4.0从使用PHP作为Web服务的mysql数据库中获取数据。我以以下格式返回JSON数据:-

{
"result": [
    {
        "category_Id": 1,
        "category_Name": "Jyotirling",
        "category_Image": "jyotirling.jpg",
        "total_Mandir": 12
    },
    {
        "category_Id": 2,
        "category_Name": "Akshardham",
        "category_Image": "akshardham.jpg",
        "total_Mandir": 2
    },
    {
        "category_Id": 3,
        "category_Name": "AshtaVinayak",
        "category_Image": "ashtavinayak.jpg",
        "total_Mandir": 8
    }
],
"message": "Data found",
"status": "200"
}

我的Pojo课程是

1)

public class MandirCategory {

    @SerializedName("result")
    @Expose
    private List<MandirCategoryResults> result = null;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("status")
    @Expose
    private String status;

    public List<MandirCategoryResults> getResult() {
        return result;
    }

    public void setResult(List<MandirCategoryResults> result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

2)嵌套数据的结果类

public class MandirCategoryResults {
    @SerializedName("category_Id")
    @Expose
    private Integer categoryId;
    @SerializedName("category_Name")
    @Expose
    private String categoryName;
    @SerializedName("category_Image")
    @Expose
    private String categoryImage;
    @SerializedName("total_Mandir")
    @Expose
    private Integer totalMandir;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryImage() {
        return categoryImage;
    }

    public void setCategoryImage(String categoryImage) {
        this.categoryImage = categoryImage;
    }

    public Integer getTotalMandir() {
        return totalMandir;
    }

    public void setTotalMandir(Integer totalMandir) {
        this.totalMandir = totalMandir;
    }
}

但是现在我迷失了如何在recyclerview中访问嵌套类的数据。

我可以像这样在recyclerview中访问message属性:

String msg = listData.get(i).getMessage();

但是如何获得categoryName的价值?

编辑: 用于获取JSON数据的代码

 @GET("getMandirCategories.php")
 Call<List<MandirCategory>> getMandirCategoriesREST();

1 个答案:

答案 0 :(得分:0)

您是否要使用RecyclerView呈现列表? 如果不正确,则假设解析正确,则应该可以工作(indexMandirCategory表示List中的索引):

String category = listData.get(i).getResult().get(indexMandirCategory).getCategoryName();