错误日志说 List<dynamic>
不是 List<String>
的子类型,也就是我们在country的实体类中直接给 cities 属性赋值为 cities: json['cities']
,我们先来看看 json['cities']
是什么类型:
factory Country.fromJson(Map<String, dynamic> json) {
print(‘json[“cities”] type is ${json[‘cities’].runtimeType}’);
return Country(name: json[‘name’], cities: json[‘cities’]);
}
输出如下:
flutter: json[“cities”] type is List
这个时候我们需要将 Country.fromJson(...)
方法作如下更改:
factory Country.fromJson(Map<String, dynamic> json) {
print(‘json[“cities”] type is ${json[‘cities’].runtimeType}’);
var originList = json[‘cities’];
List cityList = new List.from(originList);
return Country(name: json[‘name’], cities: cityList);
}
上述代码中,我们创建了一个 List<String>
类型的数组,然后将 List<dynamic>
数组中的元素都添加到了 List<String>
中。输出如下:
flutter: json[“cities”] type is List
flutter: country name is China
对象嵌套
定义一个 shape.json ,格式如下:
{
“name”: “rectangle”,
“property”: {
“width”: 5.0,
“height”: 10.0
}
}
实体如下:
class Shape {
String name;
Property property;
Shape({this.name, this.property});
factory Shape.fromJson(Ma