簡體   English   中英

如何遍歷嵌套的 json object 數組

[英]How to Iterate through nested json object array

我對 Json 解析非常陌生。 我必須遍歷 json 數組 object。

我的 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',
      }
    ]
  };
}

基本上我正在做的是 abc 是酒店的名稱,並且 abc 擁有的子類別列表填充在其中。subCategory 也有類型列表。

問題是該酒店下可能有很多類型。 所以我需要在 Dart 中有一個適當的循環結構,它可以通用來處理它。

我已經成功解析了主數組,但我無法解析子類別並在子類別下鍵入。

這就是我迭代的方式:

  @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'],
          ));
        }
      }
    }
  }

這是我的 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});

}

我的容器:

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

在 RestaurantCard class 中:這是我顯示數據的方式:

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

請幫忙

提前致謝。

這就是我迭代列表長度的意思,我添加了一個代碼,您可以從中了解如何解析。

更新代碼

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

輸出

每次要檢查節點時,都應該使用原語 Object.entries 和 Object.keys。

我將在這里留下一個簡短的例子:

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

使用此腳本,您可以隨心所欲地使用 go。

如果您遇到任何問題,請告訴我。

祝你今天過得愉快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM