Solved: how can i fetch nested json data

Question

Asked by Sujan on January 13, 2022 (source).

#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

Answer

Question answered by user10456190 (source).

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;
    }
  }
DART-NULL-SAFETY FLUTTER JSON
SHARE: