首页 > 解决方案 > 如何循环 Json 数据?

问题描述

这是我的 json 结构。

[
    [
      {
       "nos": 0,
        "name": "A S MUSIC AND DANCE A CULTURAL ORGANIZATION",
         "unique_id": "AN/2020/0259067",
         "reg_details": [
                      {
                        "registered_with": "Registrar of Societies"
                      },
                      {
                        "type_of_ngo": "Registered Societies (Non-Government)"

这工作正常。

 String jsonString = await _loadANgoAsset();
    final jsonResponse = json.decode(jsonString);
    String name = jsonResponse[0][0]['name'];
    debugPrint("Name of NGO is $name");

但是,当我想使用此代码循环遍历各种数据实体的键时:

   List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
    allNamesOfNGO.forEach((allNamesOfNGO) {
      (allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
        print(key);
        (value as Map<String, dynamic>).forEach((key2, value2) {
          print(key2);
          print(value2);
        });
      });
    });

出现以下错误:

E/flutter ( 4683): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'

请帮忙!

标签: jsonflutter

解决方案


 List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];

此行尝试将第一个 ngo(String) 的名称分配给 allNamesOfNGO(List),从而导致上述错误。要克服此错误,请将上面的代码替换为:

List<dynamic> allNamesOfNGO = jsonResponse[0];
allNamesOfNGO.forEach((allNamesOfNGO) {
  (allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
    print(key);
    print(value);
    if(key == "reg_details") {
      value.forEach(regDetail) {
        print(regDetail);
      });
    }
  });
});

您不需要最里面的 forEach 循环,因为您已经在该循环之前获得了键值对。在最里面的 forEach 循环中,您尝试遍历单个键,例如 nos、name 和 unique_is(它是字符串或 int),这是不可能的。reg_details的值是一个列表。所以你可以循环遍历它,但为此你必须检查 if key == "reg_details"


推荐阅读