一、使用dart:convert
手动序列化
user.dart
import 'dart:conbert'
class User {
final String name;
final String password;
User(this.name, this.password);
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
password = json['password'];
}
}
var userMap = json.decode(userJson);
User user = User.fromJson(userMap);
二、使用代码库json_annotation
序列化
pubspec.yaml添加第三方库
dependencies:
json_annotation: ^2.4.0
dev_dependencies:
build_runner: ^1.2.8
json_serializable: ^3.0.0
CommitComment.dart
import 'package:json_annotation/json_annotation.dart';
part 'CommitComment.g.dart';
//这个标注是告诉生成器,这个类是需要生成Model类的
@JsonSerializable()
class CommitComment{
int id;
String body;
//这个标注是将后台返回的key转成我们自己想要的key
@JsonKey(name: "created_at")
DateTime createdAt;
@JsonKey(name: "html_url")
String htmlUrl;
User user;
int totalCommits;
List<RepoCommit> commits;
CommitComment(
this.id,
this.body,
this.createdAt,
this.htmlUrl,
this.user,
this.totalCommits,
this.commits
);
factory CommitComment.fromJson(Map<String, dynamic> json) => _$CommitCommentFromJson(json);
Map<String, dynamic> toJson() => _$CommitCommentToJson(this);
}
这么写完后下面3处都会报错,但没事,
//格式为 part '该类的类名.g.dart'; 这个类后面通过命令行自动生成
part 'Branch.g.dart';
//JSON转模型的方法
factory Branch.fromJson(Map<String, dynamic> json) => _$BranchFromJson(json);
//模型转JSON的方法
Map<String, dynamic> toJson() => _$BranchToJson(this);
编译器里终端运行下面命令,之后等待创建CommitComment.g.dart文件就行
flutter packages pub run build_runner build
终端输出成功信息
[INFO] Succeeded after 838ms with 2 outputs (2 actions)