是否存在类似C#、Java的JSON自动映射到模型类的解决方案?
Dart JSON 到模型类自动映射可选方案
以下是除json_serializable+build_runner组合外的3种常用实现方案,可根据你的项目场景选择:
1. 无构建步骤的运行时自动映射方案
使用基于反射封装的映射库,不需要额外执行构建命令,也不需要手动编写映射逻辑:
- 仅需给模型类添加对应序列化注解,自定义字段映射关系直接通过注解配置,嵌套对象、枚举、特殊字段转换都可自动处理
- 示例用法:
给模型类添加序列化注解,特殊字段加映射配置:
反序列化直接调用全局方法即可:@jsonSerializable class Order{ @JsonProperty(name: 'id') String? orderId; @JsonConverter(customerNameConverter) String? customerName; @JsonProperty(name: 'fulfillment.startTime') String? fulfilmentStartTime; @JsonProperty(name: 'fulfillment.endTime') String? fulfilmentEndTime; int? totalItems; String? shortCode; String? orderNumber; String? status; }
增删字段时仅需修改模型类的属性和对应注解即可,无需调整其他映射逻辑。Order order = JsonMapper.deserialize<Order>(jsonStr);
2. 轻量代码生成方案
可选择比json_serializable更简洁的代码生成类库,需要执行构建命令,但无需手动编写任何映射逻辑:
- 模型类代码量比
json_serializable少40%以上,支持嵌套映射、深拷贝、自定义转换等能力 - 增删字段时仅需调整模型类属性,重新执行一次构建命令即可自动更新映射逻辑,不会出现手动修改映射导致的拼写错误、漏改问题
- 性能优于运行时反射方案,适合对接大规模JSON数据集、迭代频繁的场景。
3. 无第三方依赖的手动映射简化方案
如果不想引入额外第三方依赖,可封装通用JSON路径取值工具简化手动映射逻辑,降低出错概率:
/// 按路径从JSON中取值,支持嵌套路径如 "customer.firstName" T getValueByPath<T>(Map<String, dynamic> json, String path, [T? defaultValue]) { final segments = path.split('.'); dynamic current = json; try { for (final seg in segments) { if (current is! Map || !current.containsKey(seg)) { return defaultValue as T; } current = current[seg]; } return current as T; } catch (e) { return defaultValue as T; } }
调整后的fromJson逻辑:
Order.fromJson(Map<String, dynamic> json) : orderId = getValueByPath(json, 'id'), customerName = '${getValueByPath(json, 'customer.firstName')} ${getValueByPath(json, 'customer.lastName')}', fulfilmentStartTime = getValueByPath(json, 'fulfillment.startTime'), fulfilmentEndTime = getValueByPath(json, 'fulfillment.endTime'), totalItems = getValueByPath(json, 'totalItems'), shortCode = getValueByPath(json, 'shortCode'), orderNumber = getValueByPath(json, 'orderNumber'), status = getValueByPath(json, 'status');
该方案无需额外依赖,增删字段时仅需新增/删除对应行的取值逻辑即可,比原生层层嵌套写[]的方式出错概率低很多。
内容的提问来源于stack exchange,提问作者Edung Divinefavour
相关产品推荐
相关产品推荐

