Flutter
使用 json_annotation
和 json_serializable
處理 json數(shù)據(jù)
-
pubspec.yaml
添加如下:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
json_annotation: ^3.0.1
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.7.2
json_serializable: ^3.2.5
- 新建
model
類,參考:https://pub.dev/packages/json_serializable#-example-tab-
如下:
import 'package:json_annotation/json_annotation.dart';
part 'Person.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);
}
1悔据、初次創(chuàng)建
Person.dart
的時候庄敛,需要加入part 'Person.g.dart';
2、在需要轉(zhuǎn)換的實體dart 類
前加入@JsonSerializable(nullable: false)
注解科汗,標識需要json序列化
處理
3表谊、fromJson()
澳叉、toJson()
方法的寫法是固定模式,按模板修改即可
4沐鼠、Person.g.dart
和文件名
需要保持一致涎显,否則執(zhí)行以下命令無效
-
cd 到根目錄坤检,執(zhí)行
flutter packages pub run build_runner build
指令生成Person.g.dart
文件
若生成 *.g.dart 報錯?
- 清除之前生成的文件
flutter packages pub run build_runner build clean
- 直接執(zhí)行下面的命令:
flutter packages pub run build_runner build --delete-conflicting-outputs
- 再重新生成 .g.dart
flutter packages pub run build_runner build