Flutter | Json自动反序列化——json_serializable v1.5.1

前言

Google推出flutter这样一个新的高性能跨平台(Android,ios)快速开发框架之后,被业界许多开发者所关注。我在接触了flutter之后发现这个确实是一个好东西,好东西当然要和大家分享,对吧。

今天要跟大家分享的是Json反序列化的实现。相信做app的同学都会遇到这么一个问题,在向服务器请求数据后,服务器往往会返回一段json字符串。而我们要想更加灵活的使用数据的话需要把json字符串转化成对象。由于flutter只提供了json to Map。而手写反序列化在大型项目中极不稳定,很容易导致解析失败。所以今天给大家介绍的是flutter团队推荐使用的 json_serializable 自动反序列化。

你将学到什么

  • flutter中如何解析json对象
  • 如何使用自动生成工具生成代码
  • 如何测试你的数据

开始json反序列化

第一步:创建mock数据

在实际开发过程中,我们可能会对之前的一些代码进行修改。当我们代码功能复杂并且量足够大的时候,我们需要使用单元测试来保证新添加的代码不会影响之前所写的代码。而服务器的数据经常会变化,所以第一步当然是创建一个我们的mock数据啦。

这里使用了GITHUB/HackerNews的数据(https://github.com/HackerNews/API)

abstract class JsonString{
  static final String mockdata = ''' {
  "by" : "dhouston",
  "descendants" : 71,
  "id" : 8863,
  "kids" : [ 8952, 9224, 8917, 8884, 8887, 8943, 8869, 8958, 9005, 9671, 8940, 9067, 8908, 9055, 8865, 8881, 8872, 8873, 8955, 10403, 8903, 8928, 9125, 8998, 8901, 8902, 8907, 8894, 8878, 8870, 8980, 8934, 8876 ],
  "score" : 111,
  "time" : 1175714200,
  "title" : "My YC app: Dropbox - Throw away your USB drive",
  "type" : "story",
  "url" : "http://www.getdropbox.com/u/2/screencast.html"
}''';
}

第二步:添加依赖

在pubspec.yaml中添加如下依赖

dependencies:
  # Your other regular dependencies here
  json_annotation: ^1.2.0

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: ^0.10.2
  json_serializable: ^1.5.1

这里需要添加三个依赖,它们分别是:”json_annotation” “build_runner” 和 “json_serializable”。

请注意,yaml配置文件对于缩进要求十分严格,下面的build_runner和json_serializable应该是与flutter_test平级的,千万不要写在flutter_test缩进后,这样它会认为这两个是flutter_test的子集目录!

由于很多朋友在这一步遇到了问题,这里贴出源码

第三步:根据json创建实体类

我们这里根据上面的json数据写好了一个dart的实体类

class Data{
  final String by;
  final int descendants;
  final int id;
  final List<int> 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});
}

我们在这里使用了dart语法糖创建了构造函数。具体请参考(https://www.dartlang.org/guides/language/language-tour#using-constructors)。

第四步:关联实体类文件

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

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<int> 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<int> 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


运行成功后我们应该能在这个实体类的下面发现一个新的文件


这个data.g.dart就是build_runner根据JsonSerializable生成的json解析文件。
我们来看看这个生成的dart文件

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'data.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Data _$DataFromJson(Map<String, dynamic> json) {
  return Data(
      by: json['by'] as String,
      descendants: json['descendants'] as int,
      id: json['id'] as int,
      kids: (json['kids'] as List)?.map((e) => e as int)?.toList(),
      score: json['score'] as int,
      time: json['time'] as int,
      title: json['title'] as String,
      type: json['type'] as String,
      url: json['url'] as String);
}

Map<String, dynamic> _$DataToJson(Data instance) => <String, dynamic>{
      'by': instance.by,
      'descendants': instance.descendants,
      'id': instance.id,
      'kids': instance.kids,
      'score': instance.score,
      'time': instance.time,
      'title': instance.title,
      'type': instance.type,
      'url': instance.url
    };

同志们请注意这段代码最上面的注释”// GENERATED CODE – DO NOT MODIFY BY HAND”。你可千万别手写生成文件啊哈哈哈哈。

这段代码生成实体类库的一个part,在老版本part中有一个抽象实体类的mixin,dart中使用基于mixin的继承来解决单继承的局限性。

新版本中声称了两个方法,fromJson和toJson方法,它们能干什么相信大家从名字上就能猜到了。

【对part感兴趣的同学可以参考https://juejin.im/post/5b601f40e51d4519575a5036#heading-8 Dart | 浅析dart中库的导入与拆分。

对mixin感兴趣的同学可以在(https://www.dartlang.org/guides/language/language-tour#adding-features-to-a-class-mixins)了解更多关于mixin的知识。】

  • _$DataFromJson:它接收了一个map:Map,并将这个Map里的值映射为我们所需要的实体类对象。我们就可以使用这个方法,将存有json数据的map转化为我们需要的实体类对象。
  • _$DataToJson:将调用此方法的对象直接根据字段映射成Map。

而这两个都是私有方法,part让两个文件共享作用域与命名空间,所以我们需要将生成的方法暴露给外部。

然后我们再回到实体类中将 添加fromJson 和 toJson方法。

import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class Data{
  final String by;
  final int descendants;
  final int id;
  final List<int> 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});
//反序列化
  factory Data.fromJson(Map<String, dynamic> json) => _$DataFromJson(json);
//序列化
  Map<String, dynamic> toJson() => _$DataToJson(this);
}
  • 提供一个工厂构造方法Data.fromJson,该方法实际调用生成文件的DataFromJson方法。
  • 提供一个toJson()序列化对象的方法,实际调用生成文件的_$DataToJson()方法,并将调用对象解析生成Map。

这样Json反序列化的工作就完成啦!

第六步:JSON反序列化

我们刚才实现了Map to Dart,可是我们需要的是json to dart。这时候就需要dart自带的 dart:convert 来帮助我们了。

dart:convert

dart:convert是dart提供用于在不同数据表示之间进行转换的编码器和解码器,能够解析JSON和UTF-8。

也就是说我们需要先将json数据使用dart:convert转成Map,我们就能通过Map转为dart对象了。

使用方法

Map<String ,dynamic> map = json.decode("jsondata");

知道了如何将jsonString解析成map以后我们就能直接将json转化为实体对象啦。

转化方法

    Data data = Data.fromJson(json.decode('jsondata'));

第七步:编写单元测试

flutter给我们提供了单元测试,它的好处在于,我们想要验证代码的正确性不用跑整个程序,每次只用跑一个单元测试文件。而且养成习惯编写单元测试以后,能够保证以后在开发过程中快速精确定位错误,避免新加入的代码破坏老的代码引起项目崩溃。每次应用启动前都会跑一遍单元测试以确保项目能够正确运行。在实际开发中我们应该使用的mock数据来作为测试数据来源。

使用方法
右键run这个测试文件

import 'dart:convert';

import 'package:flutter_test/flutter_test.dart';
import 'package:wmkids/data/mockdata.dart';
import 'package:wmkids/data/data.dart';

void main(){
  group('jsonparse test', (){
    test('mockdata test', (){
      Data data1 = Data.fromJson(json.decode(JsonString.mockdata));
      expect(data1.url, 'http://www.getdropbox.com/u/2/screencast.html');
    });
  });
}

我们使用到了第一步创建的mock数据,并验证了该json的url,假如我们解析正确这个单元测试将会通过。

这里的group是一组测试,一个group中可以有多个test验证我们的代码是否正确。

expect(data1,data2);会check我们的data1与data2的值是否相等,假如一样的话就会通过测试。假如不一样的话会告诉我们哪里不一样。

常用场景特殊处理办法

对象嵌套场景下的json解析

在json中经常会使用嵌套信息,我们在解析成dart文件的时候需要解析成对象嵌套。在这种场景下需要将编写步骤做一个调整。
我们需要在编写实体类的时候就带上工厂方法,因为对象存在依赖关系,先要保证子对象是serializable的才能保证父对象成功解析。


这里提示有错误时正常的,然后再生成文件。

自定义字段

我们可以通过JsonKey自定义参数进行注释并自定义参数来自定义各个字段。例如:是否允许字段为空等。注意,这里不加任何JsonKey默认允许空json字段。

例如:


这里的json使用了“-”作为字段名,而dart中只允许字母数字下划线作为变量名。所以我们必须对它进行特殊处理。@JsonKey(name=”Nicehash-CNHeavy”)来解析map。


然后再生成文件。


我们可以发现,生成文件已经将map中的NicehashCNHeavy替换成了Nicehash-CNHeavy。

泛型情况

github源码参考

https://github.com/Vadaski/Vadaski-flutter_note_book/tree/master/mecury_project/example/flutter_auto_json_parsing

写在最后

以上就是Flutter Json自动反序列化的全部内容,文章若有不对之处欢迎各位大牛指正!关于泛型问题若有更好的解决方案希望能在评论区告诉我^-^。