【问题标题】:get value from nested json array and check if it is empty or not in flutter从嵌套的 json 数组中获取值并检查它是否为空或不颤动
【发布时间】:2020-05-14 14:09:45
【问题描述】:

我的 json 数组看起来像:

[
    {
        "sub_categories": [],
        "category_id": "82",
        "catgory_name": "Andrew Murray 1 Month",
        "parent_cat_id": "1"
    },
    {
        "sub_categories": [
            {
                "category_id": "177",
                "catgory_name": "2 Samuel",
                "parent_cat_id": "167"
            }
        ],
        "category_id": "167",
        "catgory_name": "The Bible ASV",
        "parent_cat_id": "1"
    },
]

首先我想在列表视图中显示“catgory_name”,如果该 catgory_name 有 sub_categories 数组,那么我需要在另一个列表中显示它,那么我该如何实现这一点。 我通过以下代码获取所有类别名称:

 class CategoryModel {
      final String name;
      final List<SubCategoryModel> SubCategory;

      CategoryModel({
        this.name,
        this.SubCategory,
      });

      factory CategoryModel.fromJson(Map<String, dynamic> json) {
        return new CategoryModel(
          name: json['catgory_name'].toString(),
          SubCategory: parsesub_categories(json['sub_categories']),
         // SubCategory:(json['sub_categories'] as List).map((map) => map).toList(),
        );

      }
static List<SubCategoryModel> parsesub_categories(cateJson) {
    List<SubCategoryModel> catlist = new List<SubCategoryModel>.from(cateJson);
    return catlist;
  }

但是 sub_categories 我无法获得该数组。

【问题讨论】:

  • parsePlaces 是做什么的?您是否尝试过检查 json['sub_categories'] 是否有效?查看this关于在 Flutter 中序列化对象的文章
  • 我更新问题请看
  • @urvashi 你有为 SubCategoryModel 写的课程吗?
  • 您不能使用List.from 直接创建SubCategoryModel 类型的列表。您需要为SubCategoryModel 使用自定义的fromJson 方法,就像您对CategoryModel 使用的方法一样

标签: json flutter


【解决方案1】:

您可以创建如下数据模型:

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 数组解析为数据模型数组

  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,
      )

【讨论】:

    【解决方案2】:

    您可以使用QuickType.io 为 json 生成 dart 类 (PODO)。

    import 'dart:convert';
    
    List<CategoryModel> categoryModelFromJson(String str) => List<CategoryModel>.from(json.decode(str).map((x) => CategoryModel.fromJson(x)));
    
    String categoryModelToJson(List<CategoryModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class CategoryModel {
        List<CategoryModel> subCategories;
        String categoryId;
        String catgoryName;
        String parentCatId;
    
        CategoryModel({
            this.subCategories,
            this.categoryId,
            this.catgoryName,
            this.parentCatId,
        });
    
        factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
            subCategories: json["sub_categories"] == null ? null : List<CategoryModel>.from(json["sub_categories"].map((x) => CategoryModel.fromJson(x))),
            categoryId: json["category_id"],
            catgoryName: json["catgory_name"],
            parentCatId: json["parent_cat_id"],
        );
    
        Map<String, dynamic> toJson() => {
            "sub_categories": subCategories == null ? null : List<dynamic>.from(subCategories.map((x) => x.toJson())),
            "category_id": categoryId,
            "catgory_name": catgoryName,
            "parent_cat_id": parentCatId,
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多