繁体   English   中英

如何在 Flutter 中解析嵌套的 JSON 数组?

[英]How to parse nested JSON Array in Flutter?

我正在使用 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: (context, snapshot) {
    if (snapshot.hasError) {
      return Center(child: Text('Error: ${snapshot.error}'));
    } else if (snapshot.hasData) {
      List<Users> users = snapshot.data;
      return ListView.separated(
        separatorBuilder: (_, __) => const Divider(),
        itemCount: users.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('${users[index].username}'),
            subtitle: Text('${users[index].images[index].imageName}'),
            onTap: () {
              Navigator.pushNamed(
                context,
                DetailsScreen.route,
                arguments: users[index],
              );
            },
          );
        },
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  },
),

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

这是一个简单的对象,我不考虑你的数组。 它只是内部对象模型。 你可以通过这个生成模型: 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;
    }
    }

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

不好:

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

好的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM