I am trying to fetch data from REST API with nested items. JSON structure looks like:
[
{
"userId": 0,
"title": "",
"items": [
{
"name": ""
}
],
"cardData": {
"name": ""
}
}
]
I am trying to create a model for this. I am not sure how album should look here for these two objects. Can someone give me advice?
final int userId;
final String title;
final List<Item> items;
final CardData cardData;
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
title: json['title'],
);
}
CodePudding user response:
IMO you'd better create a model that fits your use case instead copying/pasting a model that comes from an external API.
That being said, if you do want to have a Dart model that maps your REST API, what you can do is:
final int userId;
final String title;
final List<Item> items;
final CardData cardData;
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
title: json['title'],
items: json['items'].map((item) => Item.fromJson(item)).toList(),
cardData: CardData.fromJson(json['cardData'])
);
}