Android(安卓)flutter Json转Dart Model类
16lz
2021-12-04
Android flutter Json转Dart Model类
自动生成Model
json_serializable
1. pubspec.yaml
dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 json_serializable: ^3.3.0dev_dependencies: flutter_test: sdk: flutter build_runner: ^1.10.0 json_serializable: ^3.3.0
build_runner是dart团队提供的一个生成dart代码文件的外部包
2. lib代码
example.dart
import 'package:json_annotation/json_annotation.dart';part 'example.g.dart';@JsonSerializable(nullable: false)class Person { final String firstName; final String lastName; final DateTime dateOfBirth; Person({this.firstName, this.lastName, this.dateOfBirth}); factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json); Map<String, dynamic> toJson() => _$PersonToJson(this);}
3. 运行代码生成器自动生成Model类
在当前项目的根目录下运行:
flutter packages pub run build_runner build
运行成功,在lib文件夹下生成example.g.dart
这个example.g.dart就是build_runner根据JsonSerializable生成的json解析文件
与example.dart相对应的example.g.dart内代码如下:
part of 'example.dart';Person _$PersonFromJson(Map<String, dynamic> json) { return Person( firstName: json['firstName'] as String, lastName: json['lastName'] as String, dateOfBirth: DateTime.parse(json['dateOfBirth'] as String), );}Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{ 'firstName': instance.firstName, 'lastName': instance.lastName, 'dateOfBirth': instance.dateOfBirth.toIso8601String(), };
4. 序列化和反序列化
JSON反序列化
将JSON格式的字符串转为Dart对象:
通过dart:convert中内置的JSON解码器json.decode()方法可以根据JSON字符串具体内容将其转为List或Map,通过Map转为Dart对象
Map<String, dynamic> map = json.decode(json);Person person = Person.fromJson(map);
参考链接:
https://pub.dev/packages/json_serializable
https://book.flutterchina.club/chapter11/json_model.html
https://www.jianshu.com/p/b307a377c5e8
更多相关文章
- android_intent
- Android(安卓)studio Dialog 弹出式对话框
- Android(安卓)CreateBitmap
- android使用ANT打包,签名,混淆
- android 访问SQLite
- 为Activity生成桌面快捷方式
- Android(安卓)keytool 生成证书MD5指纹
- 关于Android证书申请配置
- Android(安卓)命令行手动编译打包详解