Flutter 中的 JSON 解析 (1),androidsdk 环境配置
person_service.dart
import 'package:flutter/services.dart';import 'dart:convert';import 'dart:async';import '../models/person.dart';
// 读取 assets 文件夹中的 person.json 文件 Future<String> _loadPersonJson() async {return await rootBundle.loadString('assets/person.json');}
// 将 json 字符串解析为 Person 对象 Future<Person> decodePerson() async {// 获取本地的 json 字符串 String personJson = await _loadPersonJson();
// 解析 json 字符串,返回的是 Map<String, dynamic> 类型 final jsonMap = json.decode(personJson);
print('jsonMap runType is ${jsonMap.runtimeType}');
Person person = Person.fromJson(jsonMap);
print('person name is {person.age}, height is ${person.height}');
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<String> 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<String> _loadCountryJson() async {return await rootBundle.loadString('assets/country.json');}
Future<Country> 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() 运行,报错了...
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'...
错误日志说 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<dynamic>
这个时候我们需要将 Country.fromJson(...)
方法作如下更改:
factory Country.fromJson(Map<String, dynamic> json) {print('json["cities"] type is ${json['cities'].runtimeType}');var originList = json['cities'];List<String> cityList = new List<String>.from(originList);return Country(name: json['name'], cities: cityList);}
上述代码中,我们创建了一个 List<String>
类型的数组,然后将 List<dynamic>
数组中的元素都添加到了 List<String>
中。输出如下:
flutter: json["cities"] type is List<dynamic>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(Map<String, dynamic> json) {
return Shape(name: json['name'], property: json['property']);
}
}
class Property {
double width;
double height;
Property({this.width, this.height});
factory Property.fromJson(Map<String, dynamic> json) {
return Property(width: json['width'], height: json['height']);
}
}
Service 类如下:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
import '../models/shape.dart';
Future<String> _loadShapeJson() async {
return await rootBundle.loadString('assets/shape.json');
}
Future<Shape> decodeShape() async {
String shapeJson = await _loadShapeJson();
Map<String, dynamic> jsonMap = json.decode(shapeJson);
Shape shape = Shape.fromJson(jsonMap);
print('shape name is ${shape.name}');
return shape;
}
运行之后,会报如下错误:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Property'
也就是说 property: json['property']
这里赋值的类型是 _InternalLinkedHashMap<String, dynamic>
而不是 Property
,json['property']
的值是这样的 {width: 5.0, height: 10.0}
,它是一个 Map ,并不是一个 Property
对象,我们需要先将这个 Map 转化为对象,然后在赋值:
factory Shape.fromJson(Map<String, dynamic> json) {
print('json["property"] is ${json['property']}');
Property property = Property.fromJson(json['property']); // new linereturn Shape(name: json['name'], property: property);
}
输出:
shape name is rectangle
复杂的对象数组嵌套
{"id": "0302","class_name": "三年二班","students": [{"name": "叶湘伦","sex": "男"},{"name": "路小雨","sex": "女"}]}
实体:
class ClassInfo {String id;String name;List<Student> studentList;
ClassInfo({this.id, this.name, this.studentList});
factory ClassInfo.fromJson(Map<String, dynamic> json) {return ClassInfo(id: json['id'],name: json['class_name'],studentList: json['students']);}}
class Student {String name;String sex;
Student({this.name, this.sex});
factory Student.fromJson(Map<String, dynamic> json) {return Student(name: json['name'], sex: json['sex']);}}
service:
import 'dart:async';import 'dart:convert';import 'package:flutter/services.dart';import '../models/class_info.dart';
Future<String> _loadClassInfoJson() async {return await rootBundle.loadString('assets/class_info.json');}
Future<ClassInfo> decodeClassInfo() async {String classInfoJson = await _loadClassInfoJson();
Map<String, dynamic> jsonMap = json.decode(classInfoJson);
ClassInfo classInfo = ClassInfo.fromJson(jsonMap);classInfo.studentList.forEach((student) => print('student name is ${student.name}'));return classInfo;}
评论