how can i fetch nested json data

108

Shouldn't you use the fromJson method that you have declared in the CategoryModel?

*edit

Something like this:

loadedData.add(CategoryModel.fromJson(element));

**edit

How to filter data?

     Future<void> fetchCategory(BuildContext context) async{
    const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
    try{
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body);
      print(extractedData);
      List<CategoryModel> loadedData = [];
      if(extractedData == null){
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text("Data is Null failed to fetch data!"),
          duration: Duration(seconds: 3),));
      }
      extractedData.forEach((element){
        // Something like this to filter the elements before adding to list.
        final item = CategoryModel.fromJson(element);
        if(item.on_sale == true){
            loadedData.add(CategoryModel.fromJson(element));
        }

        });
      _cItems = loadedData;
      print(_cItems);
      notifyListeners();
    }catch(e){
      rethrow;
    }
  }
Share:
108
Saurav
Author by

Saurav

Updated on January 03, 2023

Comments

  • Saurav
    Saurav over 1 year

    #I am able to fetch id name address but i am not able to fetch image which is src which is inside image need help #This is my model class

    class CategoryModel with ChangeNotifier{
      CategoryModel({
        this.id,
        this.name,
        this.slug,
        this.parent,
        this.description,
        this.display,
        this.image,
        this.menuOrder,
        this.count,
        this.yoastHead,
        this.yoastHeadJson,
        this.links,
      });
    
      int? id;
      String? name;
      String? slug;
      int? parent;
      String? description;
      String? display;
      Image? image;
      int? menuOrder;
      int? count;
      String? yoastHead;
      YoastHeadJson? yoastHeadJson;
      Links? links;
    
      factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
        id: json["id"],
        name: json["name"],
        slug: json["slug"],
        parent: json["parent"],
        description: json["description"],
        display: json["display"],
        image: json["image"] == null ? null : Image.fromJson(json["image"]),
        menuOrder: json["menu_order"],
        count: json["count"],
        yoastHead: json["yoast_head"],
        yoastHeadJson: YoastHeadJson.fromJson(json["yoast_head_json"]),
        links: Links.fromJson(json["_links"]),
      );
    
      Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "slug": slug,
        "parent": parent,
        "description": description,
        "display": display,
        "image": image == null ? null : image!.toJson(),
        "menu_order": menuOrder,
        "count": count,
        "yoast_head": yoastHead,
        "yoast_head_json": yoastHeadJson!.toJson(),
        "_links": links!.toJson(),
      };
    }
    
    class Image {
      Image({
        this.id,
        this.dateCreated,
        this.dateCreatedGmt,
        this.dateModified,
        this.dateModifiedGmt,
        this.src,
        this.name,
        this.alt,
      });
    
      int? id;
      DateTime? dateCreated;
      DateTime? dateCreatedGmt;
      DateTime? dateModified;
      DateTime? dateModifiedGmt;
      String? src;
      String? name;
      String? alt;
    
      factory Image.fromJson(Map<String, dynamic> json) => Image(
        id: json["id"],
        dateCreated: DateTime.parse(json["date_created"]),
        dateCreatedGmt: DateTime.parse(json["date_created_gmt"]),
        dateModified: DateTime.parse(json["date_modified"]),
        dateModifiedGmt: DateTime.parse(json["date_modified_gmt"]),
        src: json["src"],
        name: json["name"],
        alt: json["alt"],
      );
    
      Map<String, dynamic> toJson() => {
        "id": id,
        "date_created": dateCreated!.toIso8601String(),
        "date_created_gmt": dateCreatedGmt!.toIso8601String(),
        "date_modified": dateModified!.toIso8601String(),
        "date_modified_gmt": dateModifiedGmt!.toIso8601String(),
        "src": src,
        "name": name,
        "alt": alt,
      };
    }
    

    #This is how i try to fetch data. i am trying to fetch data and store that data in a list so that i can render that data according to my design

      Future<void> fetchCategory(BuildContext context) async{
        const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
    
        try{
          final response = await http.get(Uri.parse(url));
          final extractedData = json.decode(response.body);
          print(extractedData);
          List<CategoryModel> loadedData = [];
          if(extractedData == null){
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
              content: Text("Data is Null failed to fetch data!"),
              duration: Duration(seconds: 3),));
          }
          extractedData.forEach((element){
            loadedData.add(CategoryModel(
              id:element['id'],
              name:element['name'],
              image: element['image']['src']
              // image: element!['image']
              // image: element['image']==null?Text("no Image to show"):element['image']['src']
            ));
          });
          _cItems = loadedData;
          print(_cItems);
          notifyListeners();
        }catch(e){
          rethrow;
        }
      }
    

    #But i am unable to fetch image Image is in nested data like this

    [
    {id: 25, 
    name: Bakery, 
    slug: bakery, 
    parent: 0, 
    description: , 
    display: products, 
    image: {
         id: 83, 
         date_created: 2021-07-16T12:16:24, 
         date_created_gmt: 2021-07-16T12:16:24, 
         date_modified: 2021-07-16T12:16:24, 
         date_modified_gmt: 2021-07-16T12:16:24, 
         src: https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-content/uploads/2021/07/Intersection.png, 
         name: Intersection, 
        alt: 
      }
    ]
    

    #I wanna fetch the src inside Image

  • Saurav
    Saurav over 2 years
    hmm meaning i didnt get what u actually meant to say
  • user10456190
    user10456190 over 2 years
    I updated my response. Additionally, you could generate a CategoryModels class which would hold all the CategoryModels and have a fromJson method, so you wouldn't need to use the for-loop.
  • Saurav
    Saurav over 2 years
    but can i ask u one more question like what to do if i wanna filter the data show only specific detail on the screen?
  • user10456190
    user10456190 over 2 years
    He already has fromJson and toJson functions in his classes.
  • user10456190
    user10456190 over 2 years
    You can access the item details through loadedData-list. loadedData[index].id loadedData[index].name loadedData[index].slug loadedData[index].parent and so on...
  • Saurav
    Saurav over 2 years
    like can i do this or not? extractedPublishedData.forEach((element) { if(element['on_sale'] == true) { loadedPublishedModel.add(ProductModel.fromJson(element)); } });
  • Saurav
    Saurav over 2 years
    or like if (element['meta_data']['value'] == 'New Product') checking nested data like this?
  • user10456190
    user10456190 over 2 years
    I would convert the json data to Dart model and then access the data. Using the CategoryModel.fromJson or similar method. I updated the example above.
  • Saurav
    Saurav over 2 years
    ok thanks i got it thanks for help