【发布时间】:2021-07-04 18:14:06
【问题描述】:
这是我的 json:
{
"data": {
"id": 1,
"title": "Test-1",
"description": "Description of test-1.",
"category_id": "1",
"product_sizes": [
{
"id": 24,
"name": "name",
"created_at": "2021-06-28T09:50:12.000000Z",
"updated_at": "2021-06-28T09:50:12.000000Z",
"pivot": {
"product_id": "1",
"size_id": "24"
}
}
],
"stock_images": [
{
"id": 13,
"product_id": "1",
"stock_id": "109",
"color_id": "1",
"meta": {
"small": "image_path",
"medium": "image_path",
"large": "image_path"
},
},
{
"id": 14,
"product_id": "1",
"stock_id": "110",
"color_id": "2",
"meta": {
"small": "image_path",
"medium": "image_path",
"large": "image_path"
},
},
],
"category": {
"id": 27,
"title": "Category_title",
}
},
}
我的api调用如下:
static Future<Test> getTest(int id) async{
final response = await client.get(Uri.parse("URL_HERE"));
if(response.statusCode == 200){
Map<String, dynamic> json = jsonDecode(response.body);
dynamic body = json['data'];
Test test = Test.fromJson(body);
return test;
}
else{
throw("Couldnot get product detail from the server");
}
}
下面是模型类:
class Test {
final int id;
final String title;
final String description;
final List<StockImage>? stockImages;
Test({
required this.id,
required this.title,
required this.description,
required this.stockimages
});
factory Test.fromJson(Map<String, dynamic> parsedJson) {
return Test(
id: parsedJson["id"],
title: parsedJson["title"],
stockImages: List<StockImage>.from(parsedJson["stock_images"].map((l)=>
StockImage.fromJson(l))),
);
}
}
class StockImage {
final int id;
final String productId;
final String stockId;
final String colorId;
final List<Meta>? meta;
StockImage({
required this.id,
required this.productId,
required this.stockId,
required this.colorId,
this.meta,
});
factory StockImage.fromJson(Map<dynamic, dynamic> json){
return StockImage(
id : json["id"] as int,
productId : json["product_id"] as String,
stockId : json["stock_id"] as String,
colorId : json["color_id"] as String,
meta: List<Meta>.from(json["meta"].map((l)=>Meta.fromJson(l))),
);}
}
class Meta{
final String small;
final String medium;
final String large;
Meta({
required this.small,
required this.medium,
required this.large
});
factory Meta.fromJson(Map<String, dynamic> json) {
return Meta(
small : json['small'] as String,
medium : json['medium'] as String,
large : json['large'] as String
);}
}
我不确定我是否采用了有效的方法来创建模型类,但请就我的问题向我提问,因为我可能遗漏了一些东西。我正在尝试从 Meta 类中获取图像列表。提前谢谢!
【问题讨论】: