【发布时间】: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<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]
]
}
【问题讨论】:
-
你能提供更多你的代码吗?
matrix是List<List<double>>吗? -
@easeccy 是的矩阵是
List<List<double>>。这是顶级声明。class Matrix { int rows; int cols; List<List<double>> matrix; } -
你的 json 结构是怎样的?
-
@easeccy 我在上面添加了我的 JSON 序列化版本。