Dart:如何将 CSV 数据映射到模型列表?

Dart: How to map CSV data to a list of a model?

假设,在文件 crops.csv 中,我有一个格式如下的简单数据集:

id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange

我有一个名为 foodCrops 的模型 Class:

class foodCrops {
  int id;
  String cropType;
  String cropName;

  foodCrops(this.id, this.cropType, this.cropName);
}

如何将这些数据从 csv 文件转换为 classfoodCrops 列表?

List<foodCrops> 

最简单的方法可能是将文件作为行列表读取,然后使用 map 执行转换。

final crops = File.readAsLinesSync('path/to/crops.csv')
                  .skip(1) // Skip the header row
                  .map((line) {
                    final parts = line.split(',');
                    return FoodCrops(
                      int.tryParse(parts[0]),
                      parts[1],
                      parts[2],
                    );
                  )
                  .toList();

在这里,我只是解析行以创建 FoodCrop class 的实例。您可以随意解析数据。

void main() {
  var foodCrops = makeFoodCropList();
  for (var foodCrop in foodCrops) {
    print(foodCrop);
  }
}

List<FoodCrop> makeFoodCropList() {
  var lines = [
    'id,cropType,cropName',
    '1,food,rice',
    '2,cash,sugarcane',
    '3,horticulture,orange',
  ];
  lines.removeAt(0); //remove column heading

  /*
  * you can use any parser for csv file,
  *
  * a csv package is available
  * or simple file reading will also get the job done main logic is coded here
  * */

  var list = <FoodCrop>[];
  for (var line in lines) list.add(FoodCrop.fromList(line.split(',')));

  return list;
}

class FoodCrop {
  int id;
  String cropType;
  String cropName;

  FoodCrop(this.id, this.cropType, this.cropName);

  FoodCrop.fromList(List<String> items) : this(int.parse(items[0]), items[1], items[2]);

  @override
  String toString() {
    return 'FoodCrop{id: $id, cropType: $cropType, cropName: $cropName}';
  }
}

另一种方法。

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final list = data.skip(1).map((e) => FoodCrops(int.parse(e[0]), e[1], e[2]));
  print(list.join('\n'));
}

const _source = '''
id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
''';

class FoodCrops {
  int id;
  String cropType;
  String cropName;

  FoodCrops(this.id, this.cropType, this.cropName);

  @override
  String toString() {
    return '$id $cropType $cropName';
  }
}

输出:

1 food rice
2 cash sugarcane
3 horticulture orange