Flutter 如何序列化和反序列化2D矩阵?
我有一个矩阵类,我想添加序列化和反序列化方法 这是我到目前为止尝试的实现Flutter 如何序列化和反序列化2D矩阵?,flutter,dart,dart-pub,Flutter,Dart,Dart Pub,我有一个矩阵类,我想添加序列化和反序列化方法 这是我到目前为止尝试的实现 //连载 映射到JSON(){ 返回{ “行”:行, “cols”:cols, “矩阵”:矩阵, }; } //反序列化 fromJson(映射json){ this.rows=json['rows']; this.cols=json['cols']; var mat=json['matrix']; //this.matrix=(jsonMap['matrix']作为列表).map((i)=>matrix.fromJso
//连载
映射到JSON(){
返回{
“行”:行,
“cols”:cols,
“矩阵”:矩阵,
};
}
//反序列化
fromJson(映射json){
this.rows=json['rows'];
this.cols=json['cols'];
var mat=json['matrix'];
//this.matrix=(jsonMap['matrix']作为列表).map((i)=>matrix.fromJson(i)).toList();
//this.matrix=List.from((mat)=>List.from(i));
列表映射器(m){
var x=列表的起始值(m);
打印(x.runtimeType);
返回x;
}
打印(json['matrix'].map(mapper.toList().runtimeType);
}
静态字符串序列化(矩阵mat){
返回jsonEncode(mat);
}
静态矩阵反序列化(字符串jsonString){
Map mat=jsonDecode(jsonString);
var result=Matrix.fromJson(mat);
返回结果;
}
在上面的fromJson
函数中,它无法将返回类型检测为List
,而是将其检测为List
,因为我无法在矩阵中设置其值
编辑:我在下面添加了我的Matrix
类的基本版本
//矩阵类
类矩阵{
int行;
int cols;
列表矩阵;
矩阵(整数行,整数列){
this.rows=行;
this.cols=cols;
this.matrix=List.generate(行,()=>List(cols));
这个;
}
矩阵一(){
对于(int i=0;i
编辑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)))),
};
factory Matrix.fromJson(映射json)=>Matrix(
行:json[“行”],
cols:json[“cols”],
矩阵:List.from(json[“matrix”].map((x)=>List.from(x.map((x)=>x.toDouble())),
);
映射到JSON()=>{
“行”:行,
“科尔斯”:科尔斯,
“矩阵”:列表.from(矩阵.map((x)=>List.from(x.map((x)=>x)),
};
您能提供更多的代码吗?是矩阵
是列表
?@easecy是矩阵是列表
。下面是顶级声明<代码>类矩阵{int rows;int cols;List Matrix;}您的json是如何构造的?@easeccy我已经在上面添加了json的序列化版本。