【问题标题】:How to parse nested JSON Array in Flutter?如何在 Flutter 中解析嵌套的 JSON 数组?
【发布时间】:2019-12-30 20:17:38
【问题描述】:

我正在使用 json_model 插件来制作 PODO 类。我已经成功解析了主数组。但是我无法使用该插件将包含 Map 数组的“图像”键放入 PODO 类中,并且无法解析数据。

这是我要解析的数组。

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    },
    "images": [
      {
        "id": 11,
        "imageName": "xCh-rhy"
      },
      {
        "id": 31,
        "imageName": "fjs-eun"
      },
      {
        "id": 51,
        "imageName": "asd-fdg"
      },
      {
        "id": 71,
        "imageName": "zxc-cvb"
      },
      {
        "id": 91,
        "imageName": "qwe-hgj"
      }
    ]
  },
    ...
]

谢谢!!!

这里解析json数据

Future<List<Users>> _fetchUser() async {
    final response =
        await DefaultAssetBundle.of(context).loadString('users.json');
    if (response != null) {
      List users = json.decode(response.toString());
      return users.map((user) => Users.fromJson(user)).toList();
    } else {
      throw Exception('Failed to load data!');
    }
  }

正在尝试显示“图像”数据...

FutureBuilder<List<Users>>(
          future: _fetchUser(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else if (snapshot.hasData) {
              List<Users> users = snapshot.data;

              return ListView.separated(
                itemCount: users.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text('${users[index].username}'),
                    subtitle: Text('${users[index].images[index].imageName}'),
                    onTap: () {
                      Navigator.pushNamed(context, DetailsScreen.route,
                          arguments: users[index]);
                    },
                  );
                },
                separatorBuilder: (BuildContext context, int index) =>
                    Divider(),
              );
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        )

但它显示错误:索引超出范围:索引应小于 5:5

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这是一个简单的对象,我不考虑你的数组。它只是内部对象模型。 您可以通过以下方式生成模型:https://javiercbk.github.io/json_to_dart/

        class Autogenerated {
        int id;
        String name;
        String username;
        String email;
        Address address;
        String phone;
        String website;
        Company company;
        List<Images> images;
    
        Autogenerated(
            {this.id,
            this.name,
            this.username,
            this.email,
            this.address,
            this.phone,
            this.website,
            this.company,
            this.images});
    
        Autogenerated.fromJson(Map<String, dynamic> json) {
            id = json['id'];
            name = json['name'];
            username = json['username'];
            email = json['email'];
            address =
                json['address'] != null ? new Address.fromJson(json['address']) : null;
            phone = json['phone'];
            website = json['website'];
            company =
                json['company'] != null ? new Company.fromJson(json['company']) : null;
            if (json['images'] != null) {
            images = new List<Images>();
            json['images'].forEach((v) {
                images.add(new Images.fromJson(v));
            });
            }
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['id'] = this.id;
            data['name'] = this.name;
            data['username'] = this.username;
            data['email'] = this.email;
            if (this.address != null) {
            data['address'] = this.address.toJson();
            }
            data['phone'] = this.phone;
            data['website'] = this.website;
            if (this.company != null) {
            data['company'] = this.company.toJson();
            }
            if (this.images != null) {
            data['images'] = this.images.map((v) => v.toJson()).toList();
            }
            return data;
        }
        }
    
        class Address {
        String street;
        String suite;
        String city;
        String zipcode;
        Geo geo;
    
        Address({this.street, this.suite, this.city, this.zipcode, this.geo});
    
        Address.fromJson(Map<String, dynamic> json) {
            street = json['street'];
            suite = json['suite'];
            city = json['city'];
            zipcode = json['zipcode'];
            geo = json['geo'] != null ? new Geo.fromJson(json['geo']) : null;
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['street'] = this.street;
            data['suite'] = this.suite;
            data['city'] = this.city;
            data['zipcode'] = this.zipcode;
            if (this.geo != null) {
            data['geo'] = this.geo.toJson();
            }
            return data;
        }
        }
    
        class Geo {
        String lat;
        String lng;
    
        Geo({this.lat, this.lng});
    
        Geo.fromJson(Map<String, dynamic> json) {
            lat = json['lat'];
            lng = json['lng'];
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['lat'] = this.lat;
            data['lng'] = this.lng;
            return data;
        }
        }
    
        class Company {
        String name;
        String catchPhrase;
        String bs;
    
        Company({this.name, this.catchPhrase, this.bs});
    
        Company.fromJson(Map<String, dynamic> json) {
            name = json['name'];
            catchPhrase = json['catchPhrase'];
            bs = json['bs'];
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['name'] = this.name;
            data['catchPhrase'] = this.catchPhrase;
            data['bs'] = this.bs;
            return data;
        }
        }
    
        class Images {
        int id;
        String imageName;
    
        Images({this.id, this.imageName});
    
        Images.fromJson(Map<String, dynamic> json) {
            id = json['id'];
            imageName = json['imageName'];
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['id'] = this.id;
            data['imageName'] = this.imageName;
            return data;
        }
        }
    

    【讨论】:

    • 非常感谢兄弟!您引导我使用更简单的方法来解析 json。您能否指导我如何在颤动中显示“图像”数组。顺便说一句,我正在使用 FutureBuilder。
    • 伙计,我来自 javascript 背景,并将这个颤振项目作为一种爱好。在我看到他们如何解码之后,我几乎放弃了。你应该因为向我展示了 GitHub 存储库而获得了一枚该死的奖章。很多爱!
    【解决方案2】:

    建议的答案是可以的,但会出现一些错误(即使在自动转换器中,在链接中提供)。例如,

    不行:

    Geo.fromJson(Map<String, dynamic> json) {
        lat = json['lat'];
        lng = json['lng'];
    }
    

    好的:

    Geo.fromJson(Map<String, dynamic> json):
        lat = json['lat'],
        lng = json['lng'];
    

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 2019-01-24
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2022-01-16
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多