颤振持久性:如何 json解码<dynamic>列表<ClassType>到列表?



我有一个带有Task类的Todo List应用程序。我想用jsonEncode序列化一个任务列表,并将它们持久化到Docs-dir中的一个文件中。之后,我希望能够重新序列化相同的列表,并将它们转换为我的本地list数据类型(来自我从jsonDecode获得的list<String,dynamic>(。最好的方法是什么?

目前,我尝试过:

void reSerializeTaskList() async {
final directory = await getApplicationDocumentsDirectory();
File f = File('${directory.path}/new.txt');
String fileContent = await f.readAsString();
List<dynamic> jsonList = jsonDecode(fileContent).cast<Task>(); // does not  work
print("JSONSTRING: ${jsonList.runtimeType}");
print("$jsonList");
}
I/flutter (29177): JSONSTRING: CastList<dynamic, Task>
E/flutter (29177): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Task' in type cast

我的解决方法是遍历所有数组元素,并用";fromJson";我的Task类中的方法:

void reSerializeTaskList() async {
final directory = await getApplicationDocumentsDirectory();
File f = File('${directory.path}/new.txt');
String fileContent = await f.readAsString();
List<dynamic> jsonList = jsonDecode(fileContent);
List<Task> taskList = [];
for (var t in jsonList) {
print("T: $t and ${t.runtimeType}");
Task task = new Task();
taskList.add(task.fromJson(t));
}
print("JSONSTRING: ${jsonList.runtimeType}");
print("$jsonList");
print("$taskList");
print("$taskList.runtimeType");
} 

我的任务类别:

import 'dart:io';
class Task {
String name;
bool isDone;
Task({this.name, this.isDone = false});
void toggleDone() {
isDone = !isDone;
}
@override
String toString() {
// TODO: implement toString
return "${this.name} is done: $isDone";
}
Map<String, dynamic> toJson() {
return {
"name": this.name,
"isDone": this.isDone,
};
}
Task fromJson(Map<String, dynamic> json) {
this.name = json['name'];
this.isDone = json['isDone'];
return this;
}
}

但还有其他(更好的(方法吗?这在我看来很不完整…

举个小例子,就是这样做的

final jsonResponse = json.decode(jsonString);
final List<Customer> customers = jsonResponse.map<Customer>((jR) => Customer.fromJson(jR)).toList();

客户类的fromJson看起来像这个

factory Customer.fromJson(Map<String, dynamic> json) => Customer(
id: json["id"] == null ? null : json["id"],
changeDate: json["changeDate"] == null ? null : DateTime.parse(json["changeDate"]),
name: json["name"] == null ? null : json["name"],
);

最新更新