arrays - 使用 Dart 语言解析嵌套的 JSON 数组并将其放入模型类中

标签 arrays json parsing dart flutter

关于我的问题here

我想解析一个在 JSON 数组中没有键的 JSON 数组,并将其放入模型类中。

这是我要解析的 JSON 数组。

[
    {
        "pk": 100,
        "user": 5,
        "name": "Flutter",
        "details": "Fluttery",
        "images": [
            89,
            88,
            87,
            86
        ],
        "priority": 5
    },
    {
        "pk": 99,
        "user": 5,
        "name": "",
        "details": "h",
        "images": [],
        "priority": 5
    },
    {
        "pk": 98,
        "user": 5,
        "name": "Flutter",
        "details": "Fluttery",
        "images": [
            85
        ],
        "priority": 5
    },
]

我已成功解析主数组,但无法解析包含整数数组的 images 键。我想把它放到模型类中。请帮忙。

谢谢!

最佳答案

你可以这样做:

    final jsonList = json.decode(response.body) as List;
    final userList = jsonList.map((map) => User.fromJson(map)).toList();

用户类

        class User {
          final int pk;
          final String name;
          final List<int> images;

          User._({this.pk, this.name, this.images});

          factory User.fromJson(Map<String, dynamic> json) {
            return new User._(
                pk: json['pk'],
                name: json['name'],
                images:  (json['images'] as List).map((map) => int.parse("$map")).toList());
          }
        }

打印您的数据

    for (var i = 0; i < userList.length; i++) { 
       print(userList[i].name);
       final imageList = userList[i].images;
       for (var j = 0 ; j < imageList.length; j++){
          print("image: ${imageList[j]}");
       }

    }

关于arrays - 使用 Dart 语言解析嵌套的 JSON 数组并将其放入模型类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51978610/

相关文章:

java - 如何将数组转换为字符数组?

java - 对于未知数量的参数,如何格式化像 String [] {a, b, c, ... n} 这样的数组?

java - 在 Java 中构造时设置数组值

python - 提取 numpy 结构化数组的最高值

php - 令人费解的php解析器错误

java - JSON 变量名称中包含空格

php - 将以下查询显示为逗号分隔列表

javascript - Aurelia-repeat.for json

mysql - 如何使用 mvc spring 将 JSON 数组插入 MySQL

json - 如何在 Swift 上通过 Mashape 打印 JSON 数据?