Parse Nested JSON Array and put it in a Model class using Dart Language

2,616

You can do it like this way:

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

User class

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

    }
Share:
2,616
Martin Rupert Bulquerin
Author by

Martin Rupert Bulquerin

Updated on November 21, 2022

Comments

  • Martin Rupert Bulquerin
    Martin Rupert Bulquerin over 1 year

    In relation to my question here

    I want to parse a JSON array without a key within JSON array and put it in a Model class.

    here is a JSON Array that I want to parse.

    [
        {
            "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
        },
    ]
    

    I have successfully parse the main Array but I cannot parse the images key that contains an array of integers. I want to put it into Model class. please help.

    Thank you!

  • Martin Rupert Bulquerin
    Martin Rupert Bulquerin over 5 years
    cannot pass the decoded json in Map because the result using json.decode(result) is an Arrray.
  • Martin Rupert Bulquerin
    Martin Rupert Bulquerin over 5 years
    Thanks you! i will try this solution and will get back here asap. :)
  • Martin Rupert Bulquerin
    Martin Rupert Bulquerin over 5 years
    It works! but how to I call the images using nested for loop? I used this to call the name. for (var i = 0; i < userList.length; i++) { print(userList[i].name);}