将JSON对象解析为Dart中的接口

时间:2014-08-16 11:03:54

标签: json interface dart

我有一个Employee和Department接口。我正在从服务器加载JSON,我需要“解析”到实现这些接口的对象。有没有办法如何自动实现这一点,因为接口和JSON对象中的所有类型都是基类型(字符串,数字,列表,映射)?

// Abstract classes represents interfaces
abstract class Employee {
  String firstName;
  String lastName;
}

abstract class Department {
  String name;
  List<Employee> employees;
}

// JSON
{
  "name": "Development",
  "employees":
  [
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
  ]
}

我想像这样解析它

main() {
  ...
  Department department = someMethodToParse(jsonFromServer);
  ...
}