Flutter Json自动反序列化——json_serializable v1(1)

本文介绍了使用json_serializable库在Flutter中实现JSON自动反序列化的详细步骤,包括关联实体类文件、生成Json解析文件、JSON反序列化,以及编写单元测试。特别强调了build_runner在生成代码中的作用,以及dart:convert包在将JSON转换为Dart对象过程中的使用。此外,还提及了对象嵌套场景下的处理办法。
摘要由CSDN通过智能技术生成

}

我们在这里使用了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这样实体类就创建完成啦。

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

还记得我们刚才添加的build_runner的依赖吗,这时候我们就需要它来帮忙咯。

build_runner

build_runner是dart团队提供的一个生成dart代码文件的外部包。

我们在当前项目的目录下运行flutter packages pub run build_runner build<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值