Flutter如何实现CheckListPoint类型List与JSON的互相转换
实现步骤
1. 先给CheckListPoint类实现单对象JSON互转
要实现列表转换,首先得保证列表内的单个CheckListPoint对象本身支持JSON序列化和反序列化,给类补充如下方法:
class CheckListPoint { bool correctly = false; bool passed = false; String requirement = ''; // 单对象转JSON Map Map<String, dynamic> toJson() { return { 'correctly': correctly, 'passed': passed, 'requirement': requirement, }; } // 从JSON Map初始化对象 CheckListPoint.fromJson(Map<String, dynamic> json) : correctly = json['correctly'] ?? false, passed = json['passed'] ?? false, requirement = json['requirement'] ?? ''; // 无参默认构造方法保留,方便后续动态修改属性 CheckListPoint(); }
注意:使用jsonEncode、jsonDecode需要先导入Dart官方的
dart:convert库,代码中用??做默认值 fallback,避免JSON字段缺失时报错,适配后续属性动态调整的需求。
2. 实现List的JSON互转
列表转JSON字符串
直接遍历列表调用每个对象的toJson方法,再用jsonEncode序列化即可:
// 把checkListPoints转成JSON数组字符串 String checkListPointsToJson(List<CheckListPoint> points) { return jsonEncode(points.map((point) => point.toJson()).toList()); }
JSON字符串转回List
先把JSON字符串解析为List
// 把JSON数组字符串转回List<CheckListPoint> List<CheckListPoint> checkListPointsFromJson(String jsonStr) { final List<dynamic> jsonList = jsonDecode(jsonStr); return jsonList.map((jsonItem) => CheckListPoint.fromJson(jsonItem)).toList(); }
3. 结合你原有的父类方法改造
你原来的包含name、description的类里,已经有checkListPoints属性,直接修改原有toJson和fromJson方法适配即可:
// 改造后的原有类toJson方法 String toJson() { Map<String,dynamic> map = { 'name': name, 'count': checkListCount, 'description': description, // 把列表也加入序列化字段 'checkListPoints': checkListPoints.map((point) => point.toJson()).toList(), }; return jsonEncode(map); } // 改造后的原有类fromJson方法,修正了原代码参数名和使用变量名不一致的问题 fromJson(String contents) { Map<String,dynamic> map = jsonDecode(contents); name = map['name']; description = map['description']; // 解析列表 final List<dynamic> pointJsonList = map['checkListPoints'] ?? []; checkListPoints = pointJsonList.map((item) => CheckListPoint.fromJson(item)).toList(); return '0'; }
内容的提问来源于stack exchange,提问作者GDTyka
相关产品推荐
相关产品推荐

