如何序列化和反序列化二维矩阵?

How to serialize and deserialize a 2D Matrix?

我有一个矩阵 class,我想在其中添加序列化和反序列化方法。

这是我到目前为止尝试过的实施方式。


  // serialize
  Map<String, dynamic> toJson() {
    return {
      'rows': rows,
      'cols': cols,
      'matrix': matrix,
    };
  }

  // deserialize
  Matrix.fromJson(Map<String, dynamic> json) {
    this.rows = json['rows'];
    this.cols = json['cols'];
    var mat = json['matrix'];
    //this.matrix = (jsonMap['matrix'] as List).map((i) => Matrix.fromJson(i)).toList();
    //this.matrix = List<List<double>>.from((mat) => List<double>.from(i));
    List<double> mapper(m) {
      var x = List<double>.from(m);
      print(x.runtimeType);
      return x;
    }
    print(json['matrix'].map(mapper).toList().runtimeType);
  }

  static String serialize(Matrix mat) {
    return jsonEncode(mat);
  }

  static Matrix deserialize(String jsonString) {
    Map mat = jsonDecode(jsonString);
    var result = Matrix.fromJson(mat);
    return result;
  }

在上面的 fromJson 函数中,它无法将 return 类型检测为 List<List<double>>,而是将其检测为 List<dynamic>,因为我不是能够在矩阵中设置它的值。

编辑:我在下面添加了我的 Matrix class 的基本版本。

// Matrix Class
class Matrix {
  int rows;
  int cols;
  List<List<double>> matrix;

  Matrix(int rows, int cols) {
    this.rows = rows;
    this.cols = cols;
    this.matrix = List.generate(rows, (_) => List(cols));
    this.ones();
  }

  Matrix ones() {
    for(int i = 0; i < rows; i++) {
      for(int j = 0; j < cols; j++) {
        matrix[i][j] = 1.0;
      }
    }
    return this;
  }
}

编辑 2:序列化的 json 看起来像这样,

{
  "rows": 3,
  "cols": 2,
  "matrix": [
    [-0.659761529168694, -0.3484637091350998],
    [7.24485752819742, 7.197552403928113],
    [5.551818494659232, 5.600521388162702]
  ]
}

试试这个

factory Matrix.fromJson(Map<String, dynamic> json) => Matrix(
    rows: json["rows"],
    cols: json["cols"],
    matrix: List<List<double>>.from(json["matrix"].map((x) => List<double>.from(x.map((x) => x.toDouble())))),
);

Map<String, dynamic> toJson() => {
    "rows": rows,
    "cols": cols,
    "matrix": List<dynamic>.from(matrix.map((x) => List<dynamic>.from(x.map((x) => x)))),
};