Flutter中如何将递归结构JSON映射到对应递归类?
递归JSON映射到递归类的实现思路
以下两种方案都可快速实现映射,可根据项目复杂度选择:
方案1:手动编写序列化逻辑(无第三方依赖)
适合模型结构简单、不想引入额外依赖的场景:
- 第一步:给现有
Entry类新增fromJson工厂方法,遇到children节点时递归调用自身解析子项
class Entry { Entry(this.title,this.icono,[this.children = const <Entry>[]]); final String title; final String icono; final List<Entry> children; // 新增递归解析方法 factory Entry.fromJson(Map<String, dynamic> json) { final childrenJson = json['children'] as List; final childrenList = childrenJson.map((child) => Entry.fromJson(child)).toList(); return Entry( json['title'] as String, json['icono'] as String, childrenList ); } }
- 第二步:解析顶层JSON数组,批量生成Entry列表
// yourJsonString为你拿到的原始JSON字符串 List<dynamic> topJsonList = jsonDecode(yourJsonString); List<Entry> resultList = topJsonList.map((item) => Entry.fromJson(item)).toList();
无需额外写递归终止逻辑:当
children为空数组时,map方法会直接返回空列表,自动终止递归。
方案2:使用序列化生成库(适合复杂项目)
如果项目已经在使用json_serializable这类序列化生成工具,直接给Entry类加序列化标注即可:
- 给
Entry类添加@JsonSerializable()注解,工具会自动识别children的List<Entry>类型,生成的解析代码会自动处理递归逻辑 - 直接调用生成的
_$EntryFromJson方法即可完成解析,无需手动编写递归代码
内容的提问来源于stack exchange,提问作者Miguel Flores
相关产品推荐
相关产品推荐

