Flutter解析API响应后如何从嵌套列表获取指定索引元素并赋值
实现步骤
首先你需要引入Dart内置的JSON解析库,直接在文件头部导入即可:
import 'dart:convert';
接下来按以下逻辑处理接口返回的响应数据即可:
- 先将接口返回的JSON字符串解码为Dart的Map对象
- 提取
data字段的嵌套列表,按索引取值后做类型转换赋值
完整代码示例
// 假设response是你请求接口拿到的响应对象,response.body为接口返回的JSON字符串 Map<String, dynamic> resJson = jsonDecode(response.body); // 提取data字段的嵌套列表,data外层数组第一个元素就是包含目标值的内层数组 List<dynamic> innerList = (resJson['data'] as List)[0]; // 分别取值赋值到对应类型变量 String strValue = innerList[0] as String; int intValue = innerList[1] as int;
健壮性优化(可选)
如果担心接口结构变动导致崩溃,可以加类型校验和空安全处理:
Map<String, dynamic>? resJson = jsonDecode(response.body); if (resJson?['success'] == true && resJson?['data'] is List) { List dataList = resJson!['data']; if (dataList.isNotEmpty && dataList[0] is List) { List innerList = dataList[0]; if (innerList.length >= 2) { String strValue = innerList[0] is String ? innerList[0] : ''; int intValue = innerList[1] is int ? innerList[1] : 0; // 后续业务逻辑 } } }
内容的提问来源于stack exchange,提问作者Mohsin noor
相关产品推荐
相关产品推荐

