Flutter Persistence:如何将 List<dynamic> jsonDecode 到 List<ClassType>?

问题描述

我有一个带有 Task 类的 Todo-List 应用程序。 我想用 jsonEncode 序列化一个任务列表,并将它们保存到 Docs 目录中的文件中。 在那之后,我希望能够重新序列化相同的列表并将它们转换为我的本机 List 数据类型(来自我从 jsonDecode 获得的 List )。最好的方法是什么?

目前,我尝试过:

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

我的解决方法是遍历所有数组元素并使用我的 Task 类中的“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();

Customer 类中的 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"],);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...