gpt4 book ai didi

flutter - 如何序列化和反序列化2D矩阵?

转载 作者:行者123 更新时间:2023-12-03 04:59:23 25 4
gpt4 key购买 nike

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

这是我到目前为止尝试的实现。


// 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<List<double>>,而是将其检测为 List<dynamic>,因为我无法在矩阵中设置其值。

编辑:我在下面添加了我的 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]
]
}

最佳答案

试试这个

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

关于flutter - 如何序列化和反序列化2D矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59917665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com