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

2024-04-09

关于我的问题here https://stackoverflow.com/questions/51977112/parse-json-array-without-key-using-dart

我想解析 JSON 数组中没有键的 JSON 数组并将其放入 Model 类中。

这是我想要解析的 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]}");
       }

    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Dart 语言解析嵌套 JSON 数组并将其放入模型类中 的相关文章

随机推荐