Flutter中如何通过HTTP Get映射JSON的items数据?
解决Flutter中JSON数组的映射问题
问题分析
你之前的代码错误在于直接遍历整个响应的Map对象,而非定位到存储用户数据的items数组。data.forEach会遍历所有顶级键(比如items、hasMore、limit等),当处理到非数组类型的键时,就会触发类型转换错误。同时你错误地将Map的键名当作id赋值,这和JSON里的用户id字段完全不符。
修正后的代码
Future<void> _loadUsers() async { final response = await http.get( Uri.parse(_url), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.body == 'null') return; // 解析整个响应为Map Map<String, dynamic> data = jsonDecode(response.body); // 取出items数组,转换为List类型 List<dynamic> itemsList = data['items']; // 遍历items数组中的每个用户数据 for (var userMap in itemsList) { teste.add( AppUser( // JSON中的id是整数类型,转成String匹配类定义 id: userMap['id'].toString(), // 当前返回的JSON无login字段,自动赋值为null login: userMap['login'], // JSON的nome对应类中的name字段 name: userMap['nome'], // JSON的telefone对应类中的phoneNumber字段 phoneNumber: userMap['telefone'], ), ); } print(teste.length); }
关键说明
- 定位目标数组:必须先从响应Map中提取
items字段,它才是存储用户数据的数组,不要遍历整个顶级Map。 - 字段对应规则:
- JSON的
id是整数类型,需转成String才能匹配AppUser的id参数 - JSON的
nome对应AppUser的name - JSON的
telefone对应AppUser的phoneNumber - 当前返回的JSON中没有
login字段,所以login会自动赋值为null,符合类中的可选参数定义
- JSON的
可选优化:添加fromJson构造函数
为了让代码更清晰易维护,可给AppUser类添加专门的JSON映射构造函数:
class AppUser { final String id; final String? login; final String? name; final String? email; final String? situation; final String? phoneNumber; final String? password; final String? inclusionDt; final String? inclusionUs; final String? altDt; final String? altUs; final String company; const AppUser({ required this.id, this.login, this.name, this.email, this.situation, this.phoneNumber, this.password, this.inclusionDt, this.inclusionUs, this.altDt, this.altUs, this.company = 'GTFoods', }); // 新增JSON转对象的构造函数 factory AppUser.fromJson(Map<String, dynamic> json) { return AppUser( id: json['id'].toString(), login: json['login'], name: json['nome'], phoneNumber: json['telefone'], email: json['email'], situation: json['situation'], // 其他字段可根据JSON实际返回补充 ); } }
此时_loadUsers方法可简化为:
Future<void> _loadUsers() async { final response = await http.get( Uri.parse(_url), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.body == 'null') return; Map<String, dynamic> data = jsonDecode(response.body); List<dynamic> itemsList = data['items']; // 使用fromJson批量转换并添加到列表 teste.addAll(itemsList.map((userMap) => AppUser.fromJson(userMap)).toList()); print(teste.length); }
内容的提问来源于stack exchange,提问作者pedro.curti
相关产品推荐
相关产品推荐

