Search code examples
flutterdartdart-pub

How to serialize and deserialize a 2D Matrix?


I have a matrix class which I want to add serialize and deserialize methods.

And here is the implementation I tried so far.


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

In the above fromJson function it is not able to detect the return type as List<List<double>> and instead it detects it as List<dynamic> because of that I am not able to set its value in the matrix.

EDIT: I have added a bare bones version of my Matrix class below.

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

EDIT 2: The serialized json looks like this,

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

Solution

  • Try this

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