You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何过滤API返回的嵌套JSON数据?

过滤嵌套JSON响应中isBoy=true的孙辈数据

我需要处理一段API返回的嵌套JSON数据,仅保留其中isBoy=true的孙辈条目,再用ListView.builder展示。现有JSON示例如下:

{"results": {"data": {"parentName": "Vic","parentFamName": "Lo","children": [{"childName": "Mark","childCount": 2,"grandChildren": [{"grandChildName": "Kent","grandChildAge": 4,"isBoy": true},{"grandChildName": "Chris","grandChildAge": 8,"isBoy": true}]},{"childName": "Kim","childCount": 3,"grandChildren": [{"grandChildName": "Martin","grandChildAge": 6,"isBoy": true},{"grandChildName": "Thesa","grandChildAge": 4,"isBoy": false},{"grandChildName": "Beck","grandChildAge": 2,"isBoy": false}]}]}}}

已经完成了JSON解码:

final jsonResponse = jsonDecode(jsonString.body);
final parentResponse = jsonResponse['results']['data'];

接下来需要实现过滤逻辑,得到仅包含符合条件孙辈的结构。


解决方案代码

你可以通过遍历嵌套数组逐层过滤,注意不要直接修改原数据,建议创建副本存储过滤结果:

// 复制原数据基础信息,避免修改原始响应
final filteredParent = Map<String, dynamic>.from(parentResponse);

// 处理children数组,逐个过滤每个child的grandChildren
final filteredChildren = (filteredParent['children'] as List<dynamic>).map((child) {
  final filteredChild = Map<String, dynamic>.from(child);
  // 筛选出isBoy=true的孙辈
  final filteredGrandChildren = (filteredChild['grandChildren'] as List<dynamic>)
      .where((grandChild) => grandChild['isBoy'] == true)
      .toList();
  filteredChild['grandChildren'] = filteredGrandChildren;

  // 可选:如果要移除过滤后无符合条件孙辈的child,取消以下注释
  // if (filteredGrandChildren.isNotEmpty) return filteredChild;
  // return null;

  return filteredChild;
}).toList();

// 可选:配合上面的逻辑,移除空child
// filteredChildren.removeWhere((element) => element == null);

filteredParent['children'] = filteredChildren;

代码说明

  1. 复制原数据:用Map.from创建原数据副本,防止修改原始响应影响其他业务逻辑。
  2. 孙辈过滤:对每个child的grandChildren数组使用where方法筛选符合条件的条目,再转为List赋值回child对象。
  3. 空child处理:如果不需要保留过滤后无孙辈的child,可以启用注释中的逻辑,直接移除这类条目。

过滤后的filteredParent即可作为ListView.builder的数据源使用。

内容的提问来源于stack exchange,提问作者Kim Lo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:30:54