Flutter/Dart如何创建适配动态键响应体的Data Class?
适配动态外层键的Dart数据类实现方案
你的JSON结构外层是非固定字符串键,对应的值是固定结构的对象,自动生成的MyModel直接对应内层对象,但无法处理外层的动态键结构,正确的实现方式是拆分结构:
原始JSON结构
{ "I am not a fixed value":{ "malicious": true, "platforms":[ "ANY_PLATFORM" ], "threats":[ "MALWARE" ], "cache":"300s" } }
自动生成的错误代码
class MyModel { bool? malicious; List<String>? platforms; List<String>? threats; String? cache; MyModel({ this.malicious, this.platforms, this.threats, this.cache, }); MyModel.fromJson(Map<String, dynamic> json) { malicious = json['malicious']; platforms = json['platforms']; threats = json['threats']; cache = json['cache']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['malicious'] = malicious; data['platforms'] = platforms; data['threats'] = threats; data['cache'] = cache; return data; } }
正确实现方案
1. 定义内层固定结构的数据类
先把JSON中固定结构的内层对象封装成独立的数据类:
class ThreatInfo { bool? malicious; List<String>? platforms; List<String>? threats; String? cache; ThreatInfo({ this.malicious, this.platforms, this.threats, this.cache, }); ThreatInfo.fromJson(Map<String, dynamic> json) { malicious = json['malicious']; platforms = List<String>.from(json['platforms'] ?? []); threats = List<String>.from(json['threats'] ?? []); cache = json['cache']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['malicious'] = malicious; data['platforms'] = platforms; data['threats'] = threats; data['cache'] = cache; return data; } }
注意:这里对
platforms和threats做了空值处理,避免JSON中字段为null时出现类型转换错误。
2. 处理外层动态键
外层的非固定键需要用Map<String, ThreatInfo>来承载,解析和序列化示例:
import 'dart:convert'; // 解析JSON字符串 String jsonStr = '''{ "I am not a fixed value":{ "malicious": true, "platforms":[ "ANY_PLATFORM" ], "threats":[ "MALWARE" ], "cache":"300s" } }'''; Map<String, dynamic> rawJson = jsonDecode(jsonStr); Map<String, ThreatInfo> threatData = rawJson.map( (key, value) => MapEntry(key, ThreatInfo.fromJson(value as Map<String, dynamic>)), ); // 获取数据示例 ThreatInfo? firstThreat = threatData.values.first; print(firstThreat?.malicious); // 输出: true // 序列化回JSON字符串 Map<String, dynamic> serialized = threatData.map( (key, value) => MapEntry(key, value.toJson()), ); String newJsonStr = jsonEncode(serialized);
方案说明
- 内层固定结构用独立数据类
ThreatInfo封装,保证类型安全和代码复用; - 外层动态键通过
Map<String, ThreatInfo>处理,完美适配非固定键的JSON结构; - 解析时通过
map方法遍历原始JSON的键值对,将每个值转换为ThreatInfo实例。
内容的提问来源于stack exchange,提问作者kalibear
相关产品推荐
相关产品推荐

