Reputation: 225
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!
Upvotes: 3
Views: 3213
Reputation: 103421
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]}");
}
}
Upvotes: 4
Reputation: 21728
Can you please refer Serializing JSON manually using dart:convert section here. If you stilling face issues, please post the error/difficulties.
Upvotes: 0