面向对象:如何在Dart中创建含嵌套列表的cluster属性
在Dart中创建嵌套列表结构的cluster属性的最佳方式
首先,你的返回数据是一个包含聚类信息的JSON数组,结构如下:
[ {"centroid":[ 5, 5, 1, 1, 1, 1], "cluster":[ [ 5, 5, 1, 1, 1, 1 ], [ 4, 2, 1, 3, 1, 1 ] ], "clusterInd":[0]} ]
在Dart中处理这类嵌套列表结构,最佳方式是定义强类型的数据模型类,配合JSON解析逻辑,既保证类型安全,也方便后续的代码维护和扩展。以下是两种常用实现方案:
1. 手动实现数据模型与JSON转换
适合不需要频繁修改模型的场景,无需额外依赖:
class ClusterResult { final List<int> centroid; final List<List<int>> cluster; final List<int> clusterInd; ClusterResult({ required this.centroid, required this.cluster, required this.clusterInd, }); // 从JSON对象解析为ClusterResult实例 factory ClusterResult.fromJson(Map<String, dynamic> json) { return ClusterResult( centroid: List<int>.from(json['centroid']), cluster: (json['cluster'] as List) .map((innerList) => List<int>.from(innerList)) .toList(), clusterInd: List<int>.from(json['clusterInd']), ); } // 将实例转换为JSON对象 Map<String, dynamic> toJson() { return { 'centroid': centroid, 'cluster': cluster, 'clusterInd': clusterInd, }; } }
2. 使用json_serializable自动生成转换代码
适合复杂或频繁修改的模型,减少手动编写重复代码的工作量:
步骤1:添加依赖
在pubspec.yaml中添加以下依赖:
dependencies: json_annotation: ^4.8.1 dev_dependencies: build_runner: ^2.4.4 json_serializable: ^6.7.0
步骤2:定义数据模型
import 'package:json_annotation/json_annotation.dart'; part 'cluster_result.g.dart'; @JsonSerializable() class ClusterResult { final List<int> centroid; final List<List<int>> cluster; final List<int> clusterInd; ClusterResult({ required this.centroid, required this.cluster, required this.clusterInd, }); // 自动生成的JSON解析方法 factory ClusterResult.fromJson(Map<String, dynamic> json) => _$ClusterResultFromJson(json); // 自动生成的JSON转换方法 Map<String, dynamic> toJson() => _$ClusterResultToJson(this); }
步骤3:生成代码
在终端运行以下命令,自动生成cluster_result.g.dart文件:
dart run build_runner build
使用示例
无论哪种方案,你都可以这样解析原始JSON数据并访问cluster属性:
// 原始JSON数据 final rawJson = [ { "centroid": [5, 5, 1, 1, 1, 1], "cluster": [ [5, 5, 1, 1, 1, 1], [4, 2, 1, 3, 1, 1] ], "clusterInd": [0] } ]; // 解析为ClusterResult列表 final clusterResults = rawJson .map((item) => ClusterResult.fromJson(item)) .toList(); // 访问第一个结果的cluster属性 final targetCluster = clusterResults[0].cluster; print(targetCluster); // 输出: [[5, 5, 1, 1, 1, 1], [4, 2, 1, 3, 1, 1]]
这种方式的优势在于:
- 强类型检查避免运行时类型错误
- 代码结构清晰,便于维护和扩展
- 标准化的JSON转换逻辑符合Dart开发最佳实践
内容的提问来源于stack exchange,提问作者Stéphani Carol
相关产品推荐
相关产品推荐

