在我的应用程序中,我从服务器进入categories
的服务器,该服务器具有一个名为products
的数组:
{
"categories": [
{
"id": 1,
"store_id": 1,
"category_id": null,
"page_id": null,
"title": "cat_name",
"image_uri": "/uploads/store/category_images/2020/1600839088.jpg",
"created_at": "2020-09-23T02:01:28.000000Z",
"updated_at": "2020-09-23T02:01:57.000000Z",
"products": [
{
"id": 1,
"store_categories_id": 1,
"store_id": 1,
"title": "title",
"description": "111111",
//...
}
]
}
],
"slides": {
"id": 1,
"slide_1": "/uploads/store/store_sliders/2020/16025126045410.jpg",
//...
}
}
我使用上述结构创建了此类:
StoreCategories
类:
@JsonSerializable()
class StoreCategories {
final List<StoreCategoriesList> categories;
@JsonKey(nullable: true)
final Slides slides;
StoreCategories(this.categories,this.slides);
factory StoreCategories.fromJson(Map<String, dynamic> json) => _$StoreCategoriesFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesToJson(this);
}
StoreCategoriesList
类:
@JsonSerializable()
class StoreCategoriesList{
final int id;
@JsonKey(name: 'store_id')
final int storeId;
final String title;
@JsonKey(name: 'image_uri')
final String imageUri;
@JsonKey(nullable: true)
final List<ProductsList> products;
StoreCategoriesList(this.id, this.storeId, this.title, this.imageUri, this.products);
factory StoreCategoriesList.fromJson(Map<String, dynamic> json) => _$StoreCategoriesListFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesListToJson(this);
}
ProductsList
类:
@JsonSerializable()
class ProductsList {
final int id;
@JsonKey(name: 'store_categories_id')
final int storeCategoriesId;
@JsonKey(name: 'store_id')
final int storeId;
final String title;
final String description;
final String image;
final int cost;
ProductsList(this.id, this.storeCategoriesId, this.storeId, this.title, this.description, this.image, this.cost);
factory ProductsList.fromJson(Map<String, dynamic> json) => _$ProductsListFromJson(json);
Map<String, dynamic> toJson() => _$ProductsListToJson(this);
}
现在!如何将json
结构转换为类映射?
此代码不正确:
StoreCategories.fromJson(_res.response.data.map((data) => StoreCategories.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.from(data)));
答案 0 :(得分:1)
像您的_res.response.data
这样的声音已经是“地图”或“列表”权限了?
因此只需StoreCategories.fromJson(_res.response.data)
。完成!
Flutter json_serializable非常聪明,足以解码嵌套类!:)
P.S。如果您有JSON String ,请执行jsonDecode(your_json_string)
以获取地图或列表。