废话不多说,直接上干货
1. 在.yaml文件中引入以下依赖,在终端中运行 flutter pub get 命令获取依赖
dependencies:
flutter:
sdk: flutter
#使用JsonSerializable生成代码的必须要在需要生成代码的实体类前添加注解@JsonSerializable()
#使用这个注解我们必须引入json_annotation
json_annotation: ^4.0.0
dev_dependencies:
build_runner: ^2.0.0 #dart团队提供的一个生成dart代码文件的外部包
json_serializable: ^6.0.0 #json自动反序列化
2. 基本使用:
先创建模型类,再添加属性,在这个类上添加 @JsonSerializable() 注解,并添加 fromJson 和 toJson 方法。
import "package:json_annotation/json_annotation.dart";
part 'vip_open_record_model.g.dart';
@JsonSerializable() // 添加注解
class VipOpenRecordModel {
final int? orderId;
final String? orderSn;
final String? skuName;
final String? skuCode;
final int? memberType;
final String? startTime;
final String? endTime;
final String? payTime;
final num? price;
final String? payType;
final int? days;
VipOpenRecordModel({ this.orderId,
this.orderSn,
this.skuName,
this.skuCode,
this.memberType,
this.startTime,
this.endTime,
this.payTime,
this.price,
this.payType,
this.days,
});
factory VipOpenRecordModel.fromJson(Map<String, dynamic> json) => _$VipOpenRecordModelFromJson(json); // _${类名}FromJson(json) json转对象固定写法
Map<String, dynamic> toJson() => _$VipOpenRecordModelToJson(this); // _${类名}ToJson(json)对象转json固定写法 }
3. 自动生成反序列文件,控制台输入指令:
flutter packages pub run build_runner build
下面是自动生成的文件,注意:自动生成的内容不可以手动修改,如果需要增加字段,修改模型之后重新执行指令即可
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'vip_open_record_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
VipOpenRecordModel _$VipOpenRecordModelFromJson(Map<String, dynamic> json) =>
VipOpenRecordModel(
orderId: json['orderId'] as int?,
orderSn: json['orderSn'] as String?,
skuName: json['skuName'] as String?,
skuCode: json['skuCode'] as String?,
memberType: json['memberType'] as int?,
startTime: json['startTime'] as String?,
endTime: json['endTime'] as String?,
payTime: json['payTime'] as String?,
price: json['price'] as num?,
payType: json['payType'] as String?,
days: json['days'] as int?,
);
Map<String, dynamic> _$VipOpenRecordModelToJson(VipOpenRecordModel instance) =>
<String, dynamic>{
'orderId': instance.orderId,
'orderSn': instance.orderSn,
'skuName': instance.skuName,
'skuCode': instance.skuCode,
'memberType': instance.memberType,
'startTime': instance.startTime,
'endTime': instance.endTime,
'payTime': instance.payTime,
'price': instance.price,
'payType': instance.payType,
'days': instance.days,
};
4.然后就可以正常使用了:
List dataList = data;
for (var element in dataList) {
VipOpenRecordModel model = VipOpenRecordModel.fromJson(element);
openModelList.add(model);
}