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

更多相关文章

  1. android_intent
  2. Android(安卓)studio Dialog 弹出式对话框
  3. Android(安卓)CreateBitmap
  4. android使用ANT打包,签名,混淆
  5. android 访问SQLite
  6. 为Activity生成桌面快捷方式
  7. Android(安卓)keytool 生成证书MD5指纹
  8. 关于Android证书申请配置
  9. Android(安卓)命令行手动编译打包详解

随机推荐

  1. LayoutTransition 容器布局动画
  2. Android OpenGL ES(六)----进入三维在代
  3. Android(安卓)下拉刷新控件SwipeRefreshL
  4. Android UI开发【开篇导航】
  5. 转载:Android中对Log日志文件的分析
  6. 怎样写一个类似ROS的易用的android机器人
  7. Android研究笔记一-Android的价值观
  8. Android ListView滚动Item背景为黑色解决
  9. Android:Intent的理解和使用
  10. SQLite在Android中使用注意事项