return person;
}
输入如下:
flutter: jsonMap runType is _InternalLinkedHashMap<String, dynamic>
flutter: person name is jack, age is 18, height is 175.0
可以看出 json.decode(personJson)
方法返回的类型为 _InternalLinkedHashMap<String, dynamic>
,意思就是这个 Map 的 key 为 String 类型,而 value 的类型为 dynamic 的,也就是动态的,就如 person.json
中,key 都是 String 类型的,但是 value 可能是 String 、int、double 等等类型。
包含数组的对象
定义一个 country.json 如下:
{
“name”: “China”,
“cities”: [
“Beijing”,
“Shanghai”
]
}
实体类如下:
class Country {
String name;
List cities;
Country({this.name, this.cities});
factory Country.fromJson(Map<String, dynamic> json) {
return Country(name: json[‘name’], cities: json[‘cities’]);
}
}
Service 类如下:
import ‘dart:async’;
import ‘package:flutter/services.dart’;
import ‘dart:convert’;
import ‘…/models/country.dart’;
Future _loadCountryJson() async {
return await rootBundle.loadString(‘assets/country.json’);
}
Future decodeCountry() async {
String countryJson = await _loadCountryJson();
Map<String, dynamic> jsonMap = json.decode(countryJson);
Country country = Country.fromJson(jsonMap);
print(‘country name is ${country.name}’);
return country;
}
然后我们在 main() 中去调用 decodeCountry() 运行,<