内容简介:VSCode 下建立 flutter.code-snipptes添加以下代码段比如服务端叫 user_id,本地想叫 userId.
dependencies: json_annotation: ^2.0.0 dev_dependencies: build_runner: ^1.0.0 json_serializable: ^2.0.0 复制代码
2. 添加引用
import 'package:json_annotation/json_annotation.dart'; part 'your_model_file_name.g.dart'; 复制代码
3. [可选] 使用 Code Snippets
VSCode 下建立 flutter.code-snipptes
添加以下代码段
"Json Model": {
"scope": "dart",
"prefix": "fJsonModel",
"body": [
"@JsonSerializable()",
"class ${1:type} {",
"${1:type} ();",
"factory ${1:type} .fromJson(Map<String, dynamic> json) => _$${1:type} FromJson(json);",
"Map<String, dynamic> toJson() => _$${1:type} ToJson(this);",
"}"
],
"description": "Json Model"
},
复制代码
4. (通过Code Snippets) 建立以下模型
@JsonSerializable() // 关键要素 1
class MyUserModel { // 关键要素 2
int user_id; // 要解析的字段,和 server 字段同名同类型
String user_name;
String user_avatar;
MyUserModel({this.user_id, this.user_name, this.user_avatar});
//反序列化 关键要素 3
factory MyUserModel.fromJson(Map<String, dynamic> json) => _$MyUserModelFromJson(json);
//序列化 关键要素 4
Map<String, dynamic> toJson() => _$MyUserModelToJson(this);
}
复制代码
5. 服务端和本地字段不同名的处理
比如服务端叫 user_id,本地想叫 userId.
Code Snippets:
"Json key": {
"scope": "dart",
"prefix": "fJsonKey",
"body": [
"@JsonKey(name: '${1:serverKey}')",
"final ${2:type} ${3:localKey};"
],
"description": "Json key"
}
复制代码
@JsonKey(name: 'user_id') // 服务端 final int userId; // 本地 复制代码
6. 有些字段不想被解析
@JsonKey(ignore: true) final int myVar; 复制代码
7. 开启脚本转换刚才的源代码
打开终端,cd 到工程根目录
输入以下命令:
- 一次性转换
flutter pub run build_runner build 复制代码
- 循环监控转换
flutter pub run build_runner watch 复制代码
注意:循环监控可能造成模拟器 hot reload 失效,建议建模完毕后关闭。
执行完之后,会自动出现 YourModel.g.dart 类,里面就是完整的 json 解析模板代码。这个类不要修改,它是由脚本自动生成。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 懒人福音——渗透测试单行化
- 懒人高效法安装开源监控神器centreon
- 懒人必备,IntelliJ IDEA中代码一键生成
- SAPI v1.1 发布了,API 懒人福音
- 适用于键盘流、懒人、强迫症患者以及码农的究极Mac使用指南
- 懒人福利:不写代码调优深度模型,谷歌开源的「What-If」了解一下
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Pattern Recognition and Machine Learning
Christopher Bishop / Springer / 2007-10-1 / USD 94.95
The dramatic growth in practical applications for machine learning over the last ten years has been accompanied by many important developments in the underlying algorithms and techniques. For example,......一起来看看 《Pattern Recognition and Machine Learning》 这本书的介绍吧!