一.基本原理篇
1.model类
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() =>
<String, dynamic>{
'name': name,
'email': email,
};
}
2.json字符串变成model (两步)
Map userMap = json.decode(jsonStr);
var user = new User.fromJson(userMap);
print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');
3.将user对象 转换成jsonStr [我们不需要手动调用toJson这个方法,因为`JSON.encode内部会自动调用]
String json = json.encode(user);
二.工具篇
json_serializable
import 'package:json_annotation/json_annotation.dart';
part 'base_result.g.dart';
@JsonSerializable()
class BaseResult {
int status;
@JsonKey(nullable: false)
bool success;
@JsonKey(name: "nicehash-CNHeavy")
final String nicehash_CNHeavy;
String error = "";
String message = "";
dynamic object;
BaseResult({this.status, this.success, this.error, this.message, this.object});
factory BaseResult.fromJson(Map<String, dynamic> json) => _$BaseResultFromJson(json);
Map<String, dynamic> toJson() => _$BaseResultToJson(this);
}
之后运行
flutter packages pub run build_runner build
image.png
三. 在json_serializable基础上 做成Json_model插件https://github.com/flutterchina/json_model
1.注意最新版本3.0.0不支持
如下配置就可以了
dependencies:
# Your other regular dependencies here
json_annotation: ^2.0.0
dev_dependencies:
# Your other dev_dependencies here
json_model: ^0.0.2
build_runner: ^1.0.0
json_serializable: ^2.0.0
用法 切换到根目录,运行如下语句就可以[首次使用,先创建jsons目录和models目录]
flutter packages pub run json_model
用法
image.png之后运行
flutter packages pub run json_model 【Run flutter packages pub run json_model (in Flutter) or pub run json_model (in Dart VM)】
就会自动生成如下3个文件
image.png如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。
网友评论