3

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!

2 Answers 2

4

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

    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you! i will try this solution and will get back here asap. :)
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);}
0

Can you please refer Serializing JSON manually using dart:convert section here. If you stilling face issues, please post the error/difficulties.

1 Comment

cannot pass the decoded json in Map because the result using json.decode(result) is an Arrray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.