Flutter Json自动反序列化——json_serializable v1

本文详细介绍了使用json_serializable库在Flutter中实现JSON反序列化的过程,包括创建实体类、关联文件、使用build_runner生成解析代码、编写单元测试等步骤,帮助开发者高效处理JSON数据。
摘要由CSDN通过智能技术生成

final int score;
final int time;
final String title;
final String type;
final String url;

Data({this.by, this.descendants, this.id, this.kids, this.score, this.time,
this.title, this.type, this.url});
}

我们在这里使用了dart语法糖创建了构造函数。具体请参考(www.dartlang.org/guides/lang…)。

第四步:关联实体类文件

我们需要在我们的实体类中关联生成文件。

import ‘package:json_annotation/json_annotation.dart’;

part ‘data.g.dart’;

@JsonSerializable()
class Data {
final String by;
final int descendants;
final int id;
final List kids;
final int score;
final int time;
final String title;
final String type;
@JsonKey(nullable: false)
final String url;

Data({this.by, this.descendants, this.id, this.kids, this.score, this.time,
this.title, this.type, this.url});

刚写完data.g.dart的会报错,这是正常的!因为我们还没生成解析文件

  • 为了使实体类文件找到生成文件,我们需要 part ‘data.g.dart’。

第五步:生成Json解析文件

当当当…!这里开始就是重头戏了!!

我们要使用JsonSerializable生成代码的话必须要在需要生成代码的实体类前添加注解@JsonSerializable(),而要使用这个注解我们必须引入json_annotation/json_annotation.dart这个包。

import ‘package:json_annotation/json_annotation.dart’;

@JsonSerializable()
class Data{
final String by;
final int descendants;
final int id;
final List kids;
final int score;
final int time;
final String title;
final String type;
final String url;

Data({this.by, this.descendants, this.id, this.kids, this.score, this.time,
this.title, this.type, this.url});
}

这里需要注意,flutter编码规范dart文件名统一小写,这样可以避免很多问题。ok这样实体类就创建完成啦。

那么问题来了,应该如何生成代码呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值