gpt4 book ai didi

flutter - Flutter将带有数组子对象和对象的json转换为类映射

转载 作者:行者123 更新时间:2023-12-03 04:34:08 27 4
gpt4 key购买 nike

在我的应用程序中,我从服务器获取此结果,并将其放入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)));

最佳答案

听起来您的_res.response.data已经是 map 或列表了吗?
因此,只需StoreCategories.fromJson(_res.response.data)即可。做完了!
Flutter json_serializable非常聪明,可以解码嵌套的类! :)
附言如果您有JSON字符串,请执行jsonDecode(your_json_string)以获取 map 或列表。

关于flutter - Flutter将带有数组子对象和对象的json转换为类映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64400125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com