【问题标题】:How to serialize and deserialize a 2D Matrix?如何序列化和反序列化 2D 矩阵?
【发布时间】:2020-01-26 11:00:28
【问题描述】:

我有一个矩阵类,我想添加序列化和反序列化方法。

这是我目前尝试的实现。


  // 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 函数中,它无法将返回类型检测为List&lt;List&lt;double&gt;&gt;,而是将其检测为List&lt;dynamic&gt;,因为我无法在矩阵中设置其值。

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

// 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]
  ]
}

【问题讨论】:

  • 你能提供更多你的代码吗? matrixList&lt;List&lt;double&gt;&gt; 吗?
  • @easeccy 是的矩阵是List&lt;List&lt;double&gt;&gt;。这是顶级声明。 class Matrix { int rows; int cols; List&lt;List&lt;double&gt;&gt; matrix; }
  • 你的 json 结构是怎样的?
  • @easeccy 我在上面添加了我的 JSON 序列化版本。

标签: flutter dart dart-pub


【解决方案1】:

试试这个

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)))),
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2019-11-10
    • 2012-03-17
    • 2012-10-27
    相关资源
    最近更新 更多