我有两个json文件,我通过一个API检索。我想创建一个产品和类别之间的关系,以便在我的产品列表中显示类别的名称,而不是类别的id。
这里我有一个例子,我的第一个json文件,其中包含所有的产品。listing.json
[
{
"id":1461267313,
"category_id":4,
"title":"Statue homme",
"description":"...",
"price":140.00,
"images_url":{
"small":"...",
"thumb":"..."
},
"creation_date":"2019-11-05T15:56:59+0000",
"is_urgent":false
},
{
"id":1691247255,
"category_id":8,
"title":"Pc portable hp elitebook 820 g1 core i5 4 go ram 250 go hdd",
"description":"...",
"price":199.00,
"images_url":{
"small":"...",
"thumb":"..."
},
"creation_date":"2019-10-16T17:10:20+0000",
"is_urgent":false
},
]
第二个json文件包含类别categories.json
[
{
"id": 1,
"name": "Véhicule"
},
//from 1 to 11
{
"id": 11,
"name": "Enfants"
}
]
我创建了一个产品模型和一个类别模型product.dart
class Product {
int? id;
int? categoryId;
String? title;
String? description;
double? price;
ImagesUrl? imagesUrl;
String? creationDate;
bool? isUrgent;
Product(
{this.id,
this.categoryId,
this.title,
this.description,
this.price,
this.imagesUrl,
this.creationDate,
this.isUrgent});
}
category.dart
class Category {
int? id;
String? name;
Category({this.id, this.name});
}
1条答案
按热度按时间zxlwwiss1#
创建一个新的类ProductItem。转换json文件后,将产品和类别按顺序添加到新类中。
class ProductItem { final Product product; final Category category; ProductItem({required this.product, required this.category}); }