首页 文章

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

提问于
浏览
1

关于我的问题here

我想在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 键 . 我想把它放到Model类中 . 请帮忙 .

谢谢!

2 回答

  • 2

    你能参考 Serializing JSON manually using dart:convert section here . 如果您仍然面临问题,请发布错误/困难 .

  • 0

    你可以这样做:

    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());
              }
            }
    

    Print your data

    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]}");
           }
    
        }
    

相关问题