Flutter中如何将JSON转换为模型列表?
Flutter JSON转模型列表解决方案
1. 定义对应模型类
根据你的JSON结构,先创建Dart模型类(假设JSON里的data数组每个元素包含id、name、description、price、image字段):
class Product { final int id; final String name; final String description; final double price; final String image; Product({ required this.id, required this.name, required this.description, required this.price, required this.image, }); // 将单个JSON对象转为模型实例 factory Product.fromJson(Map<String, dynamic> json) { return Product( id: json['id'] as int, name: json['name'] as String, description: json['description'] as String, price: (json['price'] as num).toDouble(), image: json['image'] as String, ); } }
2. 解析JSON生成模型列表
拿到JSON数据后,按以下步骤解析成List<Product>:
// 替换成你实际的JSON字符串(比如网络请求返回内容) String rawJson = ''' { "data": [ {"id":1,"name":"模型A","description":"示例描述A","price":129.9,"image":"a.png"}, {"id":2,"name":"模型B","description":"示例描述B","price":159.9,"image":"b.png"} ] } '''; // 导入json解析工具包 import 'dart:convert'; // 解析流程 Map<String, dynamic> jsonMap = jsonDecode(rawJson); List<dynamic> dataArray = jsonMap['data']; List<Product> productList = dataArray.map((item) => Product.fromJson(item)).toList();
3. 复杂场景用自动生成工具简化开发
如果JSON结构复杂,手动写解析代码容易出错,推荐用json_serializable包自动生成解析逻辑:
- 第一步:在
pubspec.yaml添加依赖
dependencies: flutter: sdk: flutter json_annotation: ^4.8.1 dev_dependencies: build_runner: ^2.4.4 json_serializable: ^6.7.0
- 第二步:修改模型类
import 'package:json_annotation/json_annotation.dart'; part 'product.g.dart'; @JsonSerializable() class Product { final int id; final String name; final String description; final double price; final String image; Product({ required this.id, required this.name, required this.description, required this.price, required this.image, }); factory Product.fromJson(Map<String, dynamic> json) => _$ProductFromJson(json); Map<String, dynamic> toJson() => _$ProductToJson(this); }
- 第三步:运行命令生成解析代码
flutter pub run build_runner build
4. 模型列表使用示例
解析完成后,可在UI中直接使用该列表,比如用ListView展示:
ListView.builder( itemCount: productList.length, itemBuilder: (context, index) { final product = productList[index]; return ListTile( leading: Image.network(product.image), title: Text(product.name), subtitle: Text(product.description), trailing: Text('¥${product.price}'), ); }, )
内容的提问来源于stack exchange,提问作者An Tran
相关产品推荐
相关产品推荐

