Dart中Car与CelebrityProfile类的List<Car>声明正确性验证及Factory构造函数JSON解析实现
首先,先明确你的List<Car> CarList声明语法上是完全正确的!不过这里给个小建议:Dart的编码规范里,类成员变量推荐使用小驼峰命名法(lowerCamelCase),所以建议把Name改成name、YOB改成yob、CarList改成carList,这样代码会更符合社区约定,可读性也更好。
接下来,我会一步步教你用Factory构造函数把给定的JSON解析成对应的Dart对象实例,直接上代码和解释:
第一步:完善类结构并添加Factory构造函数
先调整你的类,补充必要的构造函数和JSON解析逻辑:
import 'dart:convert'; // 别忘了导入这个库,用于JSON解码 class Car { String make; String model; // Factory构造函数:从JSON Map生成Car实例 factory Car.fromJson(Map<String, dynamic> json) { return Car( make: json['make'], model: json['model'], ); } // 普通构造函数(Factory构造函数需要依赖它创建实例) Car({required this.make, required this.model}); } class CelebrityProfile { String name; String yob; List<Car> carList; // Factory构造函数:从JSON Map生成CelebrityProfile实例 factory CelebrityProfile.fromJson(Map<String, dynamic> json) { // 解析嵌套的CarList:把JSON数组转成List<Car> List<Car> cars = (json['CarList'] as List) .map((carJson) => Car.fromJson(carJson)) .toList(); return CelebrityProfile( name: json['Name'], yob: json['YOB'], carList: cars, ); } // 普通构造函数 CelebrityProfile({required this.name, required this.yob, required this.carList}); }
第二步:解析完整的JSON数据
下面是把你提供的JSON字符串转换成Dart对象列表的完整逻辑:
void main() { // 你的原始JSON字符串 String rawJson = ''' {"CelebrityProfile":[{"Name":"Celeb_1","YOB":"2000","CarList":[{"make":"Lamborghini","model":"Aventador SVJ"},{"make":"Ferrari","model":"F8 Spider"}]},{"Name":"Celeb_2","YOB":"1995","CarList":[{"make":"Tesla","model":"S"},{"make":"Porsche","model":"911"},{"make":"Lamborghini","model":"Huracan EVO"}]}]} '''; // 1. 把JSON字符串解码成Dart的Map对象 Map<String, dynamic> jsonMap = jsonDecode(rawJson); // 2. 提取数组并转换成List<CelebrityProfile> List<CelebrityProfile> celebrityProfiles = (jsonMap['CelebrityProfile'] as List) .map((celebJson) => CelebrityProfile.fromJson(celebJson)) .toList(); // 测试输出,验证解析结果 for (var celeb in celebrityProfiles) { print('姓名:${celeb.name},出生年份:${celeb.yob}'); print('拥有车辆:'); for (var car in celeb.carList) { print('- ${car.make} ${car.model}'); } print('------------------------'); } }
关键注意点
- JSON键名要和解析时的取值完全匹配:你的JSON里用的是
Name、YOB、CarList(首字母大写),所以代码里不能写成小写的name或者carList,必须严格对应。 - Factory构造函数的优势:它专门负责处理外部数据到Dart对象的转换,能灵活处理嵌套结构(比如这里的
List<Car>),还可以在解析时做一些数据校验或默认值填充(比如某个字段为空时给默认值)。
内容的提问来源于stack exchange,提问作者Kenneth N
相关产品推荐
相关产品推荐

