Flutter开发之——json序列化

一 概述

  • 添加json_serializeble开发依赖
  • 根据json创建序列化类
  • 序列化后类的应用

二 添加json_serializeble开发依赖

2.1 确认Dart SDK版本(pubspec.yaml)

1
2
environment:
sdk: '>=2.12.0 <3.0.0'

2.2 json_serializable依赖(pubspec.yaml)

1
2
3
4
5
6
dependencies:
json_annotation: ^4.0.1 #json_annotation版本

dev_dependencies:
build_runner: ^2.0.3 #build_runner版本
json_serializable: ^4.1.2 #json_serializable版本

三 根据json创建序列化类

3.1 接口文件

  • API:https://www.wanandroid.com/article/list/0/json

3.2 序列化类(Article.dart)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import 'package:json_annotation/json_annotation.dart';
part 'Article.g.dart';

@JsonSerializable()
class Article {
int errorCode;
String errorMsg;
ArticleData data;
Article(this.errorCode, this.errorMsg, this.data);

factory Article.fromJson(Map<String, dynamic> json) => _$ArticleFromJson(json);
Map<String, dynamic> toJson() => _$ArticleToJson(this);

}

@JsonSerializable()
class ArticleData {
int curPage;
int offset;
bool over;
int pageCount;
int size;
int total;
List<Person> datas;

ArticleData(this.curPage, this.offset, this.over, this.pageCount, this.size, this.total, this.datas);

factory ArticleData.fromJson(Map<String, dynamic> json) => _$ArticleDataFromJson(json);
Map<String, dynamic> toJson() => _$ArticleDataToJson(this);

}

@JsonSerializable()
class Person {
String apkLink;
int audit;
String author;
bool canEdit;
int chapterId;
String chapterName;
bool collect;
int courseId;
String desc;
String descMd;
String envelopePic;
bool fresh;
String host;
int id;
String link;
String niceDate;
String niceShareDate;
String origin;
String prefix;
String projectLink;
int publishTime;
int realSuperChapterId;
int selfVisible;
int shareDate;
String shareUser;
int superChapterId;
String superChapterName;
List<Tag> tags;
String title;
int type;
int userId;
int visible;
int zan;

Person(
this.apkLink,
this.audit,
this.author,
this.canEdit,
this.chapterId,
this.chapterName,
this.collect,
this.courseId,
this.desc,
this.descMd,
this.envelopePic,
this.fresh,
this.host,
this.id,
this.link,
this.niceDate,
this.niceShareDate,
this.origin,
this.prefix,
this.projectLink,
this.publishTime,
this.realSuperChapterId,
this.selfVisible,
this.shareDate,
this.shareUser,
this.superChapterId,
this.superChapterName,
this.tags,
this.title,
this.type,
this.userId,
this.visible,
this.zan);

factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);

}

@JsonSerializable()
class Tag {
String name;
String url;

Tag(this.name, this.url);
factory Tag.fromJson(Map<String, dynamic> json) => _$TagFromJson(json);
Map<String, dynamic> toJson() => _$TagToJson(this);

}

注意:

  • 添加part 'Article.g.dart';其中:Article是dart文件名,文件名+g.dart格式
  • 在每个需要序列化的类前面添加@JsonSerializable(),如类:ArticleArticleDataPersonTag
  • 每个类里面有:变量,构造函数,类名.fromJson() => _$类名FromJson(json)toJson() => _$类名ToJson(this)

3.3 生成序列化类.g.dart文件

执行如下指令

1
flutter pub run build_runner build

如无错误发生,生成Article.g.dart文件,Article.dart文件中_$类名FromJson(json)等不会再出现错误

四 序列化后类的应用

4.1 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
late Future<Article> futureArticle;

@override
void initState() {
super.initState();
futureArticle=_httpGet2();
}

Future<Article> _httpGet2() async {
var httpClient = new HttpClient();
var uri = Uri(
scheme: 'https',
host: 'www.wanandroid.com',
path: 'article/list/0/json',
);

HttpClientRequest request = await httpClient.getUrl(uri);
HttpClientResponse response = await request.close();
String responseBody = await response.transform(utf8.decoder).join();
var jsonDecode = json.decode(responseBody);

var article =Article.fromJson(jsonDecode);
print(article);
return article;
}
//显示
FutureBuilder<Article>(
future: futureArticle,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.separated(
itemCount: snapshot.data!.data.datas.length,
separatorBuilder: (context, index) {return Divider(height: 10, color: Colors.grey,);},
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
Text("${snapshot.data!.data.datas[index].author}"),
Text("${snapshot.data!.data.datas[index].title}"),
Text("${snapshot.data!.data.datas[index].niceShareDate}")
],
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
)

4.2 效果图

五 参考

  • JSON and serialization
  • Fetch data from the internet