0

My json array looks like:

[
    {
        "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"
    },
]

First i want to display "catgory_name" in listview and if that catgory_name has sub_categories array than i need to display it in another list , so how can i achieve this. i get all catgory_name by following code:

 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;
  }

but sub_categories i could not get that array .

4
  • What does parsePlaces do? Have you tried checking if json['sub_categories'] is valid? Check out this article for serializing objects in Flutter Commented Jan 29, 2020 at 5:33
  • i update the question please see Commented Jan 29, 2020 at 5:35
  • @urvashi Do you have any class written for SubCategoryModel? Commented Jan 29, 2020 at 5:59
  • You cannot create a list of type SubCategoryModel directly by using List.from. You'll need to use a custom fromJson method for SubCategoryModel just like you have for CategoryModel Commented Jan 29, 2020 at 6:01

2 Answers 2

2

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;
  }
}

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

  List<CategoryModel> categoryList = [];

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

Now, the UI code,

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,
      )
Sign up to request clarification or add additional context in comments.

Comments

1

You can use QuickType.io to generate dart classes (PODOs) for json.

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,
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.