Flutter -解析多个json数组并设置为list

flseospp  于 2023-04-08  发布在  Flutter
关注(0)|答案(2)|浏览(115)

下面是响应体的JSON:

{
    "status": "success",
    "contents": [{
        "id": "15",
        "cname": "DOGS",
        "dogs_image": "1638695967-rtyyyt.jpg",
        "cat_image": "1638695967-jhjjj.jpg",
        "sub_category": [{
            "subcatid": "36",
            "cat_id": "15",
            "sub_category_name": "Accessories",
            "banner": null,
            "image": "1638695982-ACCESORIE.jpg"
        }, {
            "subcatid": "39",
            "cat_id": "15",
            "sub_category_name": "Beds",
            "banner": null,
            "image": "1638695982-ACCESORIE.jpg"
        }]
    }, {
        "id": "14",
        "cname": "CATS",
        "dogs_image": "1638695967-rtyyyt.jpg",
        "cat_image": "1638695967-jhjjj.jpg",
        "sub_category": [{
            "subcatid": "47",
            "cat_id": "14",
            "sub_category_name": "Accessories",
            "banner": null,
            "image": "1638695982-ACCESORIE.jpg"
        }]
    }]
}

//调用API获取上面的json数据:

Future<List<CatListData>> dashboardDataAPI(http.Client client) async {
  final response = await client.get(Uri.parse(Utilities.BASE_URL));
  List list = json.decode(response.body)['contents'];
  return parsePhotos(list.toString());
}

//将响应体转换为List的函数

List<CatListData> parsePhotos(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<CatListData>((json) => CatListData.fromJson(json)).toList();
}

// Cat列表类

class CatListData{
  final String id;
  final String cName;
  final String dogImage;
  final String catImage;
  final List<SubCatListData> subCatListDataList;

  CatListData({required this.id, required this.cName, required this.dogImage, required this.catImage, required this.subCatListDataList});

  factory CatListData.fromJson(Map<String, dynamic> json) {
    return CatListData(
      id: json['id'] as String,
      cName: json['cname'] as String,
      dogImage: json['dogs_image'] as String,
      catImage: json['cat_image'] as String,
     subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
    );
  }
}

//子类别

class SubCatListData{
  final String subCatId;
  final String catId;
  final String subCategoryName;
  final String banner;
  final String image;

  SubCatListData({required this.subCatId, required this.catId, required this.subCategoryName, required this.banner, required this.image});

  factory SubCatListData.fromJson(Map<String, dynamic> json) {
    return SubCatListData(
      subCatId: json['subcatid'] as String,
      catId: json['cat_id'] as String,
      subCategoryName: json['sub_category_name'] as String,
      banner: json['banner'] as String,
      image: json['image'] as String,
    );
  }
}

打印快照时显示空

Container(
                      child: FutureBuilder<List<CatListData>>(
                        future: dashboardDataAPI(http.Client()),
                        builder: (context, snapshot) {
                          print("Response:: "+snapshot.data.toString());
                          if (snapshot.hasData) {
                            return PhotosList(photos: snapshot.data!);
                          }else if(snapshot.hasError){
                            return const Center(
                                child: Text('An error has occurred!'),);
                          }else{
                            return const Center(
                              child: CircularProgressIndicator(),
                            );
                          }
                        },
                      ),
                    )

请让我知道如何解决这个问题并将多个JSON数组数据解析到列表中。谢谢

rbl8hiat

rbl8hiat1#

我相信问题发生在CatListData.fromJson构造函数的这一行:

subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),

你从来没有调用SubCatListData.fromJson,我相信这将更好地为您的任务工作:

subCatListDataList: (json['sub_category'] as Iterable).map<SubCatListData>(
  (value) => SubCatListData.fromJson(value as Map<String, dynamic>),
),
dgtucam1

dgtucam12#

在Flutter中使用此方法进行JSON解析

https://www.bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/

我得到了所有类型的json解析数据。

相关问题