1,添加依赖
dependencies:
json_annotation: ^2.4.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^3.0.0
2,根据接口返回json创建实体类
class HomeEntity {
String authToken;
bool showTask;
int pendingCount;
int waitCheckCount;
int checkingCount;
int checkfailCount;
HomeEntity({this.authToken, this.pendingCount,this.checkfailCount,this.checkingCount,this.showTask,this.waitCheckCount});
}
3,关联实体类文件
part 'home_entity.g.dart';
@JsonSerializable(nullable: false)
class HomeEntity {
String authToken;
bool showTask;
int pendingCount;
int waitCheckCount;
int checkingCount;
int checkfailCount;
HomeEntity({this.authToken, this.pendingCount,this.checkfailCount,this.checkingCount,this.showTask,this.waitCheckCount});
}
声明part 部分,当前项目目录下执行命令 flutter packages pub run build_runner build
Successed 后会发现dart文件目录下会生成”home_entity.g.dart“文件,这个”home_entity.g.dart“就是build_runner根据JsonSerializable生成的json解析文件,文件内容如下:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
HomeEntity _$HomeEntityFromJson(Map json) {
return HomeEntity(
authToken: json['authToken'] as String,
pendingCount: json['pendingCount'] as int,
checkfailCount: json['checkfailCount'] as int,
checkingCount: json['checkingCount'] as int,
showTask: json['showTask'] as bool,
waitCheckCount: json['waitCheckCount'] as int);
}
Map _$HomeEntityToJson(HomeEntity instance) =>
{
'authToken': instance.authToken,
'showTask': instance.showTask,
'pendingCount': instance.pendingCount,
'waitCheckCount': instance.waitCheckCount,
'checkingCount': instance.checkingCount,
'checkfailCount': instance.checkfailCount
};
4,实体类中添加fromJson 和 toJson方法
import 'package:json_annotation/json_annotation.dart';
part 'home_entity.g.dart';
@JsonSerializable(nullable: false)
class HomeEntity {
String authToken;
bool showTask;
int pendingCount;
int waitCheckCount;
int checkingCount;
int checkfailCount;
HomeEntity({this.authToken, this.pendingCount,this.checkfailCount,this.checkingCount,this.showTask,this.waitCheckCount});
factory HomeEntity.fromJson(Map json) => _$HomeEntityFromJson(json);
Map toJson() => _$HomeEntityToJson(this);
}