Flutter 中的 JSON 解析
/ 读取 assets 文件夹中的 person.json 文件// 将 json 字符串解析为 Person 对象// 获取本地的 json 字符串// 解析 json 字符串,返回的是 Map 类型print(输入如下:可以看出方法返回的类型为,意思就是这个 Map 的 key 为 String 类型,而 value 的类型为 dynamic 的,也就是动态的,就如。
person_service.dart
import ‘package:flutter/services.dart’;
import ‘dart:convert’;
import ‘dart:async’;
import ‘…/models/person.dart’;
// 读取 assets 文件夹中的 person.json 文件
Future _loadPersonJson() async {
return await rootBundle.loadString(‘assets/person.json’);
}
// 将 json 字符串解析为 Person 对象
Future 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.name}, age 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 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() 运行,报错了…
Unhandled Exception: type ‘List’ is not a subtype of type ‘List’
…
错误日志说 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(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 _loadShapeJson() async {
return await rootBundle.loadString(‘assets/shape.json’);
}
Future 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 line
return 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 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 _loadClassInfoJson() async {
return await rootBundle.loadString(‘assets/class_info.json’);
}
Future 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;
}
上述代码在运行后还是会报错:
Unhandled Exception: type ‘List’ is not a subtype of type ‘List’
同样,还是在 studentList: json['students'] 出问题了,我们把 json['students'] 的输出来看看:
[{name: 叶湘伦, sex: 男}, {name: 路小雨, sex: 女}]
上述结果的类型为 List<dynamic> 。现在我们需要将 List<dynamic> 转换到一个 List<Student> 类型的数组中,这里需要用到一个操作符 map,map 操作符的作用就是将某种类型转换为另一种类型。如下:
factory ClassInfo.fromJson(Map<String, dynamic> json) {
final originList = json[‘students’] as List;
List studentList =
originList.map((value) => Student.fromJson(value)).toList();
return ClassInfo(
id: json[‘id’], name: json[‘class_name’], studentList: studentList);
}
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。





既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
Android高级架构师
由于篇幅问题,我呢也将自己当前所在技术领域的各项知识点、工具、框架等汇总成一份技术路线图,还有一些架构进阶视频、全套学习PDF文件、面试文档、源码笔记。
- 330页PDF Android学习核心笔记(内含上面8大板块)


-
Android学习的系统对应视频
-
Android进阶的系统对应学习资料

- Android BAT部分大厂面试题(有解析)

好了,以上便是今天的分享,希望为各位朋友后续的学习提供方便。觉得内容不错,也欢迎多多分享给身边的朋友哈。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
(img-HICYufzY-1712261160575)]
-
Android学习的系统对应视频
-
Android进阶的系统对应学习资料
[外链图片转存中…(img-XvYAItwJ-1712261160576)]
- Android BAT部分大厂面试题(有解析)
[外链图片转存中…(img-hSPbJZSG-1712261160576)]
好了,以上便是今天的分享,希望为各位朋友后续的学习提供方便。觉得内容不错,也欢迎多多分享给身边的朋友哈。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
更多推荐


所有评论(0)