0

I am very new to Json parsing. I have to iterate throught json array object.

my JSON class:

  class Jsons {
  static var hotelListJson = {
    'hotelData': [
      {
        'index': 0,
        'restaurantName': 'Monginis Cake Shop',
        'foodCategory': 'The Cake Shop',
        'restReview': 5,
        'restImage': 'assets/images/Restaurant1.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
        'menuCategories': [
          {
            'categoryName': 'Pastry',
            'dishes': [
              {
                'dishName': 'Dutch Pastry',
                'price': 5,
              },
              {
                'dishName': 'Black Forest pastry',
                'price': 50,
              },
              {
                'dishName': 'Truffle Pastry',
                'price': 35,
              },
              {
                'dishName': 'Dutch Alond Veg',
                'price': 50,
              },
            ]
          },

          {
            'categoryName': 'Breads',
            'dishes': [
              {
                'dishName': 'Sandwich Bread',
                'price': 5,
              },
              {
                'dishName': 'Multigrain Bread',
                'price': 50,
              },
              {
                'dishName': 'Duth Chocolate Heart Veg (Small)',
                'price': 35,
              },
              {
                'dishName': 'Brown Bread',
                'price': 50,
              },
            ]
          },

          
          {
            'categoryName': 'Savouries',
            'dishes': [
              {
                'dishName': 'Panner pattice',
                'price': 5,
              },
              {
                'dishName': 'Veg Burger',
                'price': 50,
              },
              {
                'dishName': 'Pan Pizza Veg',
                'price': 35,
              },
              {
                'dishName': 'Veg pattice',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 1,
        'restaurantName': 'Swami Hotel',
        'foodCategory': 'Family Hotel',
        'restReview': 2,
        'restImage': 'assets/images/Restaurant2.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
        'menuCategories': [
          {
            'categoryName': 'Veg Starter',
            'dishes': [
              {
                'dishName': 'Paneer pahadi kabab',
                'price': 5,
              },
              {
                'dishName': 'Garlic chana',
                'price': 50,
              },
              {
                'dishName': 'Masala papad',
                'price': 35,
              },
              {
                'dishName': 'Manchurian',
                'price': 50,
              },
              {
                'dishName': 'Masroom chilli',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Non Veg Starter',
            'dishes': [
              {
                'dishName': 'CHI Chilli Gravy',
                'price': 5,
              },
              {
                'dishName': 'Lollypop Sezwan',
                'price': 50,
              },
              {
                'dishName': 'Pan Pizza Veg',
                'price': 35,
              },
              {
                'dishName': 'Chicken crispy',
                'price': 50,
              },
              {
                'dishName': 'Mandeli fry',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Tandoori',
            'dishes': [
              {
                'dishName': 'Chicken Tandoori',
                'price': 5,
              },
              {
                'dishName': 'Chicken Tangadi Kabab',
                'price': 50,
              },
              {
                'dishName': 'Chicken Pahadi Kabab',
                'price': 35,
              },
              {
                'dishName': 'Chicken Hydrabadi Kabab',
                'price': 50,
              },
              {
                'dishName': 'Mutton Kadhai',
                'price': 50,
              },
            ]
          },
          
          {
            'categoryName': 'NON VEG SOUP',
            'dishes': [
              {
                'dishName': 'Chi manchaow Soup',
                'price': 5,
              },
              {
                'dishName': 'Chi Clear Soup',
                'price': 50,
              },
              {
                'dishName': 'Chi Schezwan Soup',
                'price': 35,
              },
              {
                'dishName': 'Swami Special Chi Soup',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'VEG SOUP',
            'dishes': [
              {
                'dishName': 'Chicken Masala',
                'price': 5,
              },
              {
                'dishName': 'Chicken Tikka Masala',
                'price': 50,
              },
              {
                'dishName': 'Chicken Handi',
                'price': 35,
              },
              {
                'dishName': 'Butter Chicken',
                'price': 50,
              },
              {
                'dishName': 'Mutton Kadhai',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 2,
        'restaurantName': 'Smart open pick cake shop',
        'foodCategory': 'Cake Shop',
        'restReview': 1,
        'restImage': 'assets/images/Restaurant4.png',
        'distanceFromLocation': 10,
        'restStatus': 'closed',
        'offer': 'Get 5% discount',
        'menuCategories': [
          {
            'categoryName': 'CAKE HALF Kg',
            'dishes': [
              {
                'dishName': 'Black Forest',
                'price': 300,
              },
              {
                'dishName': 'Pineapple half kg',
                'price': 50,
              },
              {
                'dishName': 'Lichi half kg',
                'price': 35,
              },
              {
                'dishName': 'choco chips half kg',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'CAKE 1 KG',
            'dishes': [
              {
                'dishName': 'Butterscotch',
                'price': 5,
              },
              {
                'dishName': 'Rose falooda',
                'price': 50,
              },
              {
                'dishName': 'White forest ovenpick',
                'price': 35,
              },
              {
                'dishName': 'Mix Fruit',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 3,
        'restaurantName': 'Mitarth Chinese',
        'foodCategory': 'Chinese corner',
        'restReview': 3,
        'restImage': 'assets/images/Restaurant5.png',
        'distanceFromLocation': 20,
        'restStatus': 'open',
      },
      {
        'index': 4,
        'restaurantName': 'Selfie Chat',
        'foodCategory': 'Paani Puri & more',
        'restReview': 2,
        'restImage': 'assets/images/Restaurant6.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
      },
      {
        'index': 5,
        'restaurantName': 'Gareeb Nawaj Biryani',
        'foodCategory': 'Caterers Biryani',
        'restReview': 5,
        'restImage': 'assets/images/Restaurant7.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
      },
      {
        'index': 6,
        'restaurantName': 'Prem Sweets',
        'foodCategory': 'Sweets shop',
        'restReview': 1,
        'restImage': 'assets/images/Restaurant8.png',
        'distanceFromLocation': 40,
        'restStatus': 'closed',
        'offer': 'Get 5% discount',
      }
    ]
  };
}

Basically what I am doing is abc is name of a hotel and the list of subCategory that abc has are populated inside it.also subCategory has list of type.

The problem is there can be many Types under that hotel. So i need a proper looping structure in Dart that can be generic to handle it.

I have successfully parse the main Array but I cannot parse the subCaterory and type under subcategory.

This is How I iterate:

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < (Jsons.hotelListJson['hotelData'].length); i++) {
      var currObj = Jsons.hotelListJson['hotelData'][i];
      var currObjSubCategoryList =
          currObj['menuCategories'] as List<Map<String, Object>>;
      for (int j = 0; j < currObjSubCategoryList.length; j++) {
        var listItem = currObjSubCategoryList[j];
        var typeList = listItem['categoryName'] as List<Map<String, Object>>;
        for (int k = 0; k < typeList.length; k++) {
          var temp = typeList[k];
          var currTypeName = temp['dishes'];
          print(currTypeName);
          restaurantListModel.add(RestaurantListModel(
            currObj['restaurantName'],
            currObj['foodCategory'],
            currObj['restReview'],
            currObj['restImage'],
            currObj['distanceFromLocation'],
            currObj['restStatus'],
          ));
        }
      }
    }
  }

This is my Model class:

class RestaurantListModel {
  var name,
      category,
      review,
      offer;
  final List<String> menuCategory;

  RestaurantListModel(
      this.restaurantName,
      this.foodCategory,
      this.restReview,
      this.restImage,
      this.distanceFromLocation,
      this.restStatus,
      this.menuCategory,
      {this.offer});

}

my Container:

Container(
              //height: MediaQuery.of(context).size.height - 450,
              child: NotificationListener<OverscrollIndicatorNotification>(
                onNotification: (overscroll) {
                  overscroll.disallowGlow();
                },
                child: ListView.builder(
                    padding: EdgeInsets.only(
                        top: 10, bottom: 30, left: 15, right: 15),
                    controller: ScrollController(),
                    shrinkWrap: true,
                    itemCount: restaurantListModel.length,
                    itemBuilder: (context, index) {
                      return RestaurantCard(restaurantListModel, index,
                          restaurantListModel[index]);
                    }),
              ),
            )

In RestaurantCard class : this is how i display data :

              Padding(
              padding: const EdgeInsets.all(3.0),
              child: Container(
                alignment: Alignment.centerLeft,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.restaurantListModelObj.restaurantName,
                      style: commonTextStyle(
                          size: 2.4 * SizeConfig.textMultiplier,
                          whichFont: 'bold'),
                    ),
                    Text(
                      widget.restaurantListModelObj.foodCategory,
                      style: commonTextStyle(
                        size: 2 * SizeConfig.textMultiplier,
                      ),
                    )
                  ],
                ),
              ),
            ),

Please HELP

Thanks in advance.

2
  • if type is a list, it has a length property right, you can just do hotelListJson[`myData`][i][`subCategory'][j]['type'][k] and you can use map() function with 'type' array Commented May 9, 2021 at 6:43
  • can you please explain your answer ? Commented May 9, 2021 at 6:45

2 Answers 2

1

This is what I meant by iterating over the length of the lists, I have added a code from where you can get an idea of how you can parse.

UPDATED CODE

class Jsons {
  static var hotelListJson = {
    'hotelData': [
      {
        'index': 0,
        'restaurantName': 'Monginis Cake Shop',
        'foodCategory': 'The Cake Shop',
        'restReview': 5,
        'restImage': 'assets/images/Restaurant1.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
        'menuCategories': [
          {
            'categoryName': 'Pastry',
            'dishes': [
              {
                'dishName': 'Dutch Pastry',
                'price': 5,
              },
              {
                'dishName': 'Black Forest pastry',
                'price': 50,
              },
              {
                'dishName': 'Truffle Pastry',
                'price': 35,
              },
              {
                'dishName': 'Dutch Alond Veg',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Breads',
            'dishes': [
              {
                'dishName': 'Sandwich Bread',
                'price': 5,
              },
              {
                'dishName': 'Multigrain Bread',
                'price': 50,
              },
              {
                'dishName': 'Duth Chocolate Heart Veg (Small)',
                'price': 35,
              },
              {
                'dishName': 'Brown Bread',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Savouries',
            'dishes': [
              {
                'dishName': 'Panner pattice',
                'price': 5,
              },
              {
                'dishName': 'Veg Burger',
                'price': 50,
              },
              {
                'dishName': 'Pan Pizza Veg',
                'price': 35,
              },
              {
                'dishName': 'Veg pattice',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 1,
        'restaurantName': 'Swami Hotel',
        'foodCategory': 'Family Hotel',
        'restReview': 2,
        'restImage': 'assets/images/Restaurant2.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
        'menuCategories': [
          {
            'categoryName': 'Veg Starter',
            'dishes': [
              {
                'dishName': 'Paneer pahadi kabab',
                'price': 5,
              },
              {
                'dishName': 'Garlic chana',
                'price': 50,
              },
              {
                'dishName': 'Masala papad',
                'price': 35,
              },
              {
                'dishName': 'Manchurian',
                'price': 50,
              },
              {
                'dishName': 'Masroom chilli',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Non Veg Starter',
            'dishes': [
              {
                'dishName': 'CHI Chilli Gravy',
                'price': 5,
              },
              {
                'dishName': 'Lollypop Sezwan',
                'price': 50,
              },
              {
                'dishName': 'Pan Pizza Veg',
                'price': 35,
              },
              {
                'dishName': 'Chicken crispy',
                'price': 50,
              },
              {
                'dishName': 'Mandeli fry',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'Tandoori',
            'dishes': [
              {
                'dishName': 'Chicken Tandoori',
                'price': 5,
              },
              {
                'dishName': 'Chicken Tangadi Kabab',
                'price': 50,
              },
              {
                'dishName': 'Chicken Pahadi Kabab',
                'price': 35,
              },
              {
                'dishName': 'Chicken Hydrabadi Kabab',
                'price': 50,
              },
              {
                'dishName': 'Mutton Kadhai',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'NON VEG SOUP',
            'dishes': [
              {
                'dishName': 'Chi manchaow Soup',
                'price': 5,
              },
              {
                'dishName': 'Chi Clear Soup',
                'price': 50,
              },
              {
                'dishName': 'Chi Schezwan Soup',
                'price': 35,
              },
              {
                'dishName': 'Swami Special Chi Soup',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'VEG SOUP',
            'dishes': [
              {
                'dishName': 'Chicken Masala',
                'price': 5,
              },
              {
                'dishName': 'Chicken Tikka Masala',
                'price': 50,
              },
              {
                'dishName': 'Chicken Handi',
                'price': 35,
              },
              {
                'dishName': 'Butter Chicken',
                'price': 50,
              },
              {
                'dishName': 'Mutton Kadhai',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 2,
        'restaurantName': 'Smart open pick cake shop',
        'foodCategory': 'Cake Shop',
        'restReview': 1,
        'restImage': 'assets/images/Restaurant4.png',
        'distanceFromLocation': 10,
        'restStatus': 'closed',
        'offer': 'Get 5% discount',
        'menuCategories': [
          {
            'categoryName': 'CAKE HALF Kg',
            'dishes': [
              {
                'dishName': 'Black Forest',
                'price': 300,
              },
              {
                'dishName': 'Pineapple half kg',
                'price': 50,
              },
              {
                'dishName': 'Lichi half kg',
                'price': 35,
              },
              {
                'dishName': 'choco chips half kg',
                'price': 50,
              },
            ]
          },
          {
            'categoryName': 'CAKE 1 KG',
            'dishes': [
              {
                'dishName': 'Butterscotch',
                'price': 5,
              },
              {
                'dishName': 'Rose falooda',
                'price': 50,
              },
              {
                'dishName': 'White forest ovenpick',
                'price': 35,
              },
              {
                'dishName': 'Mix Fruit',
                'price': 50,
              },
            ]
          },
        ]
      },
      {
        'index': 3,
        'restaurantName': 'Mitarth Chinese',
        'foodCategory': 'Chinese corner',
        'restReview': 3,
        'restImage': 'assets/images/Restaurant5.png',
        'distanceFromLocation': 20,
        'restStatus': 'open',
      },
      {
        'index': 4,
        'restaurantName': 'Selfie Chat',
        'foodCategory': 'Paani Puri & more',
        'restReview': 2,
        'restImage': 'assets/images/Restaurant6.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
      },
      {
        'index': 5,
        'restaurantName': 'Gareeb Nawaj Biryani',
        'foodCategory': 'Caterers Biryani',
        'restReview': 5,
        'restImage': 'assets/images/Restaurant7.png',
        'distanceFromLocation': 40,
        'restStatus': 'open',
      },
      {
        'index': 6,
        'restaurantName': 'Prem Sweets',
        'foodCategory': 'Sweets shop',
        'restReview': 1,
        'restImage': 'assets/images/Restaurant8.png',
        'distanceFromLocation': 40,
        'restStatus': 'closed',
        'offer': 'Get 5% discount',
      }
    ]
  };
}

void main() {
  for (int i = 0; i < (Jsons.hotelListJson['hotelData']!.length); i++) {
    var currObj = Jsons.hotelListJson['hotelData']![i];
    if (currObj.containsKey('menuCategories')) {
          var currObjSubCategoryList =
        currObj['menuCategories'] as List<Map<String, Object>>;
      for (int j = 0; j < currObjSubCategoryList.length; j++) {
        var listItem = currObjSubCategoryList[j];
        var typeList = listItem['dishes']! as List<Map<String, Object>>;
        for (int k = 0; k < typeList.length; k++) {
          var temp = typeList[k];
          var currDishName = temp['dishName'];
          var currDishPrice = temp['price'];
          print("Name: " +
              currDishName.toString() +
              "\n" +
              " Price :" +
              currDishPrice.toString());
        }
      }
    }
  }
}

output

Sign up to request clarification or add additional context in comments.

9 Comments

it show me The method 'length' isn't defined for the type 'Object'. this error for j loop
now it showing The getter 'length' was called on null. Receiver: null Tried calling: length error and i am not even iterate to main array.
I added complete code now, I have shown the output on DartPad as well
getting error This requires the 'non-nullable' language feature to be enabled. Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get'. tried evrything, bt nothing working for me
it work perfectly correct on dartpad but not in my VS code
|
0

You shoulkd use the primitive Object.entries and Object.keys everytime you want to examine a node.

I'll leave a short example here:

const hotelListJSON = {
    "myData":
        [
            {
                'index':0,
                'name':'abc',
                'category':'ab',
                'review':5,
                'subCategory':
                [
                {
                 'catName': 'ab1',
                 'type':
                 [
                     {
                     'typeName':'t1',
                     'price':50,
                     }, 
                     {
                     'typeName':'t2',
                     'price':50,
                     }, 
                     {
                     'typeName':'t3',
                     'price':50,
                     }, 
                 ]
               }
               ]
            },
            
            {
                'index':1,
                'name':'abc1',
                'category':'dc',
                'review':5,
                'subCategory':
                [
                {
                 'catName': 'dc1',
                 'type':
                 [
                     {
                     'typeName':'dc',
                     'price':50,
                     }, 
                     {
                     'typeName':'dc',
                     'price':50,
                     }, 
                     {
                     'typeName':'dc',
                     'price':50,
                     }, 
                ]
                }
                ]
            },
        ]
     };
    };
    
    Object.keys(hotelListJSON).forEach((elem)=>{
      //here you have your first node
      console.log(elem);
      Object.keys(elem).forEach((elem2)=>{
      //here you have any object that is a nested object with its containing, if it is a simble element you just get the value
      console.log(elem2);
      )}
      })

With this script you can go as deep as you want.

Tell me if you encounter any problem.

Have a nice day.

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.