且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从嵌套的json数组中获取值,并检查它是否为空

更新时间:2022-04-10 07:28:29

您可以按以下方式创建数据模型:

You can create data model as below:

class CategoryModel {
  List<SubCateogryModel> subCategories;
  String categoryId;
  String catgoryName;
  String parentCatId;

  CategoryModel(
      {this.subCategories,
        this.categoryId,
        this.catgoryName,
        this.parentCatId});

  CategoryModel.fromJson(Map<String, dynamic> json) {
    if (json['sub_categories'] != null) {
      subCategories = new List<SubCateogryModel>();
      json['sub_categories'].forEach((v) {
        subCategories.add(new SubCateogryModel.fromJson(v));
      });
    }
    categoryId = json['category_id'];
    catgoryName = json['catgory_name'];
    parentCatId = json['parent_cat_id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.subCategories != null) {
      data['sub_categories'] =
          this.subCategories.map((v) => v.toJson()).toList();
    }
    data['category_id'] = this.categoryId;
    data['catgory_name'] = this.catgoryName;
    data['parent_cat_id'] = this.parentCatId;
    return data;
  }
}

class SubCateogryModel {
  String categoryId;
  String catgoryName;
  String parentCatId;

  SubCateogryModel({this.categoryId, this.catgoryName, this.parentCatId});

  SubCateogryModel.fromJson(Map<String, dynamic> json) {
    categoryId = json['category_id'];
    catgoryName = json['catgory_name'];
    parentCatId = json['parent_cat_id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['category_id'] = this.categoryId;
    data['catgory_name'] = this.catgoryName;
    data['parent_cat_id'] = this.parentCatId;
    return data;
  }
}

现在,您必须将json数组解析为数据模型数组

Now, you have to parse your json array into Data model array

  List<CategoryModel> categoryList = [];

  jsonArray.forEach((val){
      categoryList.add(CategoryModel.fromJson(val));
    });

现在,UI代码

ListView.builder(
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(categoryList[index].catgoryName),
            subtitle: categoryList[index].subCategories.isNotEmpty
                ? Column(
                    children: List.generate(
                        categoryList[index].subCategories.length, (position) {
                      String subCategory = categoryList[index]
                          .subCategories[position]
                          .catgoryName;
                      return Text(subCategory);
                    }),
                  )
                : SizedBox(),
          );
        },
        itemCount: categoryList.length,
      )