Dart如何将JSON数据转换为自定义School类实例列表?
将JSON数据转换为School类实例列表的实现方法
方法一:直接通过map转换
修改你的JSON解析代码,遍历解析后的列表,将每个JSON对象映射为School实例:
final String response = await rootBundle.loadString('assets/Schools.json'); // 明确指定data类型为List<dynamic>,避免类型警告 List<dynamic> data = json.decode(response); // 转换为School实例列表并赋值给schools变量 schools = data.map((jsonItem) => School( city: jsonItem['city'], districty: jsonItem['districty'].toUpperCase(), // 按你的期望转成全大写,不需要可删除此方法调用 name: jsonItem['name'], )).toList();
方法二:给School类添加fromJson方法(更规范易维护)
给School类添加一个静态的fromJson方法,专门负责从JSON对象转换为实例:
List <School> schools = []; List<School> allSchools() { return schools; } class School { String city; String districty; String name; School({required this.city, required this.name, required this.districty}); // 新增fromJson方法,统一处理JSON转实例逻辑 static School fromJson(Map<String, dynamic> json) { return School( city: json['city'], districty: json['districty'].toUpperCase(), name: json['name'], ); } }
然后在解析JSON时调用这个方法:
final String response = await rootBundle.loadString('assets/Schools.json'); List<dynamic> data = json.decode(response); schools = data.map((item) => School.fromJson(item)).toList();
说明
- 注意你期望的结果中部分
districty字段是全大写形式,所以代码中加入了toUpperCase()进行转换,如果需要保留JSON中的原始格式,直接去掉这个方法调用即可。 json.decode返回的是List<dynamic>,明确指定类型可以避免Dart的类型警告,让代码更严谨。
内容的提问来源于stack exchange,提问作者Emir Bolat
相关产品推荐
相关产品推荐

