Dart实体类格式
- 方案一:手写实体类
- 方案二:生产力工具:网页自动生成实体类
- 方案三:生产力工具:json_serializable使用技巧
那个方案适合我?
Dart实体类格式
class CategoryMo {
String name;
int count;
CategoryMo({this.name, this.count});
//将map转成mo
CategoryMo.fromJson(Map<String, dynamic> json) {
name = json['name'];
count = json['count'];
}
//将mo转成map,可缺省
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['count'] = this.count;
return data;
}
}
手写实体类
owner json
{
"name": "伊零Onezero",
"face": "http://i2.hdslb.com/bfs/face/1c57a17a7b077ccd19dba58a981a673799b85aef.jpg",
"fans": 0
}
model转换与使用
var ownerMap = {
"name": "伊零Onezero",
"face":
"http://i2.hdslb.com/bfs/face/1c57a17a7b077ccd19dba58a981a673799b85aef.jpg",
"fans": 0
};
Owner owner = Owner.fromJson(ownerMap);
print('name:${owner.name}');
print('fans:${owner.fans}');
print('face:${owner.face}');
网页自动生成实体类
- 通过:https://www.devio.org/io/tools/json-to-dart/ 在线生成实体类
{
"id": "5633",
"vid": "BV1q4411Y7zY",
"title": "精神病人采访实录.突然觉得他们是那么的正常…",
"tname": "影视剪辑",
"url": "https://o.devio.org/files/video/BV1yt4y1Q7SS.mp4",
"cover": "http://i1.hdslb.com/bfs/archive/4d628fdc730243c78ad393fe1ab7d6a43ab7d0c7.jpg",
"pubdate": 1557474141,
"desc": "剪自《人间世》很棒的纪录片,没做好准备千万别去看。",
"view": 1333965,
"duration": 145,
"owner": {
"name": "锦书致南辞",
"face": "http://i0.hdslb.com/bfs/face/3f79d1df624218ab9a7774682fdb1d50a407ff88.jpg",
"fans": 0
},
"reply": 2202,
"favorite": 15392,
"like": 36864,
"coin": 3344,
"share": 1841,
"createTime": "2022-11-15 12:53:27",
"size": 8161
}
json_serializable使用技巧
Step1:插件安装
dependencies:
...
dio: ^3.0.10
json_annotation: ^3.1.0
dev_dependencies:
...
json_serializable: ^3.5.0
build_runner: ^1.0.0
Step2:配置实体类
对于下面的json使用json_serializable该如何配置呢?
{
"code": 0,
"method": "GET",
"requestPrams": "dd"
}
import 'package:json_annotation/json_annotation.dart';
// result.g.dart 将在我们运行生成命令后自动生成
part 'result.g.dart';
///这个标注是告诉生成器,这个类是需要生成Model类的
@JsonSerializable()
class Result {
//定义构造方法
Result(this.code, this.method, this.requestPrams);
//定义字段
int code;
String method;
String requestPrams;
//固定格式,不同的类使用不同的mixin即可
factory Result.fromJson(Map<String, dynamic> json) => _$ResultFromJson(json);
//固定格式
Map<String, dynamic> toJson() => _$ResultToJson(this);
}
因为实体类的生成代码还不存在,所以上代码会提示一些错误是正常现象
Step3:执行build生成实体类
flutter packages pub run build_runner build
那个方案适合我?
方案 | 特点 | 适合场景 |
---|---|---|
手写实体类 | 耗时 | 小型项目且json不复杂 |
网页自动生成 | 快速、易操作 | 任何类型的项目 |
json_serializable | 需要定义字段、易维护 | 中大型项目 |
网友评论