写点什么

Flutter 中的 JSON 解析,事件分发机制 Android

用户头像
Android架构
关注
发布于: 刚刚

}


上述代码中,我们创建了一个 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> 而不是 Propertyjson['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":


《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
复制代码


"三年二班","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;}


上述代码在运行后还是会报错:


Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Student>'


同样,还是在 studentList: json['students'] 出问题了,我们把 json['students'] 的输出来看看:


[{name: 叶湘伦, sex: 男}, {name: 路小雨, sex: 女}]


上述结果的类型为 List<dynamic> 。现在我们需要将 List<dynamic> 转换到一个 List<Student> 类型的数组中,这里需要用到一个操作符 mapmap 操作符的作用就是将某种类型转换为另一种类型。如下:


factory ClassInfo.fromJson(Map<String, dynamic> json) {


final originList = json['students'] as List;


List<Student> studentList =


originList.map((value) => Student.fromJson(value)).toList();


return ClassInfo(


id: json['id'], name: json['class_name'], studentList: studentList);


}


输出:


flutter: student name is 叶湘伦 flutter: student name is 路小雨

单纯的数组

member.json


[{"id": 1,"name": "Jack"},{"id": 2,"name": "Rose"},{"id": 3,"name": "Karl"}]


实体:


class MemberList {


List<Member> memberList;


MemberList({this.memberList});


factory MemberList.fromJson(List<dynamic> listJson) {


List<Member> memberList =


listJson.map((value) => Member.fromJson(value)).toList();


return MemberList(memberList: memberList);


}


}


class Member {


int id;


String name;


Member({this.id, this.name});


factory Member.fromJson(Map<String, dynamic> json) {


return Member(id: json['id'], name: json['name']);


}


}


因为 member.json 是一个单纯的数组,所以上述代码中我们创建了一个 MemberList 类来将这个 Member 数组包含起来。


注意下上述代码中 MemberList.fromJson(...) 中的写法。


service:


import 'dart:async';import 'package:flutter/services.dart';import 'dart:convert';import '../models/member.dart';


Future<String> _loadMemberJson() async {return await rootBundle.loadString('assets/member.json');}


Future<MemberList> decodeMemberList() async {String memberListJson = await _loadMemberJson();


List<dynamic> list = json.decode(memberListJson);


MemberList memberList = MemberList.fromJson(list);


memberList.memberList.forEach((member) => print('member name is ${member.name}'));


return memberList;}


输出:


flutter: member name is Jackflutter: member name is Roseflutter: member name is Karl

复杂的 Json 解析

之前的文章 Flutter 中 ListView 的使用 中用到了 豆瓣API ,这个 API 中返回的数据包含了当前热播的电影,大家尝试着按需解析一下吧 !!!

用户头像

Android架构

关注

还未添加个人签名 2021.10.31 加入

还未添加个人简介

评论

发布
暂无评论
Flutter 中的 JSON 解析,事件分发机制Android