json_serializable
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.0
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.10.0
json_serializable: ^3.3.0
build_runner是dart团队提供的一个生成dart代码文件的外部包
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);
}
在当前项目的根目录下运行:
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(),
};
将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