05.JSON转换代码自动生成
dart
是强类型的语言,在json
的解码和编码有强类型约束要求。所以涉及到json
的转换通常都需要开发都自己去
写转换代码。这样很烦人的。好在转换的代码的规律是确定的,这样就可以通过代码的生成来实现代码的转换。
1 安装相关依赖
pubspec.yaml
# ...
dependencies:
json_annotation: ^4.6.0
json_serializable: ^6.3.1
# ...
dev_dependencies:
build_runner: ^2.0.0
# ...
下载依赖
$ flutter pub get
2 要转换的对象
import 'package:json_annotation/json_annotation.dart';
part 'directory_tree_service.g.dart'; /// <-- 要生成的文件存放位置
()
class DirectoryTreeService {
final int id;
final int pid;
final int sortId;
final String title;
Map<int, DirectoryTreeService> children = {};
DirectoryTreeService(this.id, this.pid, this.sortId, this.title);
factory DirectoryTreeService.fromJson(Map<String, dynamic> json) =>
_$DirectoryTreeServiceFromJson(json);
Map<String, dynamic> toJson() => _$DirectoryTreeServiceToJson(this);
}
3 进行生成
在命令行中执行
$ flutter pub run build_runner build
就能得到一个directory_tree_service.g.dart
的生成文件,里面就有关于DirectoryTreeService
类的json
转换代码。
生成的代码
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'directory_tree_service.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
DirectoryTreeService _$DirectoryTreeServiceFromJson(
Map<String, dynamic> json) =>
DirectoryTreeService(
json['id'] as int,
json['pid'] as int,
json['sortId'] as int,
json['title'] as String,
)..children = (json['children'] as Map<String, dynamic>).map(
(k, e) => MapEntry(int.parse(k),
DirectoryTreeService.fromJson(e as Map<String, dynamic>)),
);
Map<String, dynamic> _$DirectoryTreeServiceToJson(
DirectoryTreeService instance) =>
<String, dynamic>{
'id': instance.id,
'pid': instance.pid,
'sortId': instance.sortId,
'title': instance.title,
'children': instance.children.map((k, e) => MapEntry(k.toString(), e)),
};
4 如何使用?
/// 编码
String jsonString = jsonEncode(DirectoryTreeService(1, 0, 0, 'title'));
/// '{"id": 1, "pid": 0, "sortId": 0, "title": "title"}'
print(jsonString);
/// 解码
Map<String, dynamic> jsonMapData = jsonDecode(jsonString);
DirectoryTreeService directoryTreeService = DirectoryTreeService.fromJson(jsonMapData);