Flutter开发之——json序列化,android开发平台的框架原理
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 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(),如类:Article,ArticleData,Person,Tag -
每个类里面有:变量,构造函数,`类名.fromJso
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
n() => _KaTeX parse error: Expected group after '_' at position 32: …`,`toJson() => _̲类名ToJson(this)`
3.3 生成序列化类.g.dart文件
执行如下指令
flutter pub run build_runner build
如无错误发生,生成Article.g.dart文件,Article.dart文件中_$类名FromJson(json)等不会再出现错误
4.1 代码
late Future
@override
void initState() {
super.initState();
futureArticle=_httpGet2();
}
Future
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
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: [
更多推荐



所有评论(0)