pubspec.yaml添加三个依赖:json_annotation:添加在dependencies下,自定反序列化处理库,即用注解(元数据)处理JSON的工具:@JsonSerializable:实体类注释@JsonKey:实体类的属性注释build_runner:添加在dev_dependencies下,用来生成dart文件,所以放在dev_dependencies里json_serializable:添加在dev_dependencies下,JSON序列化处理代码如下:
dependencies:
flutter:
sdk: flutter
json_annotation: ^3.1.0
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.10.3
json_serializable: ^3.5.0
2、在lib目录新建entity目录3、以获取地址信息为例,在entity目录新建address_entity.dart(文件名最好和后台定义的类名称保持一致),同时输入下面代码:
import 'package:json_annotation/json_annotation.dart';
part 'address_entity.g.dart'; //部分引入,这个文件会自动生成
//地址实体类 自定义注解(元数据),json_annotation提供,自定义元详见 https://5.jimth.com/jiaocheng/dart/2020/0929/3999.html
@JsonSerializable()
class AddressEntity extends Object {
//自定义注解(元数据),json_annotation提供
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'userId')
String userId;
@JsonKey(name: 'province')
String province;
@JsonKey(name: 'city')
String city;
@JsonKey(name: 'county')
String county;
@JsonKey(name: 'addressDetail')
String addressDetail;
@JsonKey(name: 'tel')
String tel;
@JsonKey(name: 'isDefault')
bool isDefault;
//构造方法,语法糖传参
AddressEntity(this.id, this.name, this.userId, this.province, this.city,
this.addressDetail, this.county, this.isDefault, this.tel);
//使用此方法将JSON转成实例对象,_$AddressEntityFromJson 会在随后运行命令行生成文件中创建
factory AddressEntity.fromJson(Map<String, dynamic> srcJson) =>
_$AddressEntityFromJson(srcJson);
//使用此方法将实例对象转换成Json,_$AddressEntityToJson 会在随后运行命令行生成文件中创建
Map<String, dynamic> toJson() => _$AddressEntityToJson(this);
}
4、main.dart使用
//引入convert和entity里面创建的文件,这里是address_entity.dart
import 'dart:convert';
import 'entity/address_entity.dart';
void main() {
//json数据模拟,实际可能从接口获取
var data = '''
"id":1,
"name":"张三",
"userId":"123456789",
"province":"安徽",
"city":"合肥",
"county":"中国",
"addressDetail":"明珠广场",
"tel":"88888888888",
"isDefault":true
''';
//实例化AddressEntity类
//使用json.decode解码
//使用AddressEntity.fromJson方法将其转为实例对象
AddressEntity addressEntity = AddressEntity.fromJson(json.decode(data));
//实体对象用AddressEntity.toJson方法输出内容
print(addressEntity.toJson().toString());
}
5、在命令行定位当项目目录,运行下面的代码,生成相应的文件
flutter packages pub run build_runner build运行完上面的命令,会在entity文件夹生成一个文件:address_entity.g.dart
6、至此,全部完成。
