Flutter中的序列化

在项目开发时,我们需要将外部(网络、数据库等)读取到的数据映射成模型类,或者将数据模型类序列化成可传输或存储的格式,这个格式一般是Json或Xml。下面就以Json格式的序列化和反序列化为例,看看在Flutter中该如何做。

两种方式

  1. 小项目里用手动序列化方式
  2. 中大型项目使用代码生成方式

Flutter没有类似于GSON、Jackson、Moshi的类库,因为Flutter不支持反射。

手动序列化

使用内置的JSON解析库 dart:convert。

优点是使用方便,无需额外依赖以及特定的初始化设置。
缺点是难于管理并容易出错。比如当由于书写错误去访问一个不存在的JSON域,会导致运行时错误。

原始JSON字符串:

{
  "name": "John Smith",
  "email": "[email protected]"
}

使用jsonDecode方法解析成字典:

Map user = jsonDecode(jsonString);

print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');

解析成字典无法在编译期间准确知道数据类型,容易出错。

字典转换成普通对象:

class User {
  final String name;
  final String email;

  User(this.name, this.email);

//将字典解析逻辑转移到Model类中,经过赋值操作,可以利用编译期类型检查,检查出错误。
  User.fromJson(Map json)
      : name = json['name'],
        email = json['email'];

  Map toJson() =>
    {
      'name': name,
      'email': email,
    };
}

Map userMap = jsonDecode(jsonString);
var user = new User.fromJson(userMap);

print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');

//Model类转换成JSON字符串
String json = jsonEncode(user);

使用代码自动生成

使用json_serializable或built_value库。需要初始化。下面以json_serializable为例。

添加依赖:

//普通依赖
dependencies:
  # Your other regular dependencies here
  json_annotation: ^2.0.0

//开发依赖
dev_dependencies:
  # Your other dev_dependencies here
  build_runner: ^1.0.0
  json_serializable: ^2.0.0

新建Model类:

import 'package:json_annotation/json_annotation.dart';

/// This allows the `User` class to access private members in
/// the generated file. The value for this is *.g.dart, where
/// the star denotes the source file name.
part 'user.g.dart';

/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@JsonSerializable()

class User {
  User(this.name, this.email);

  String name;
  String email;

  /// A necessary factory constructor for creating a new User instance
  /// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
  /// The constructor is named after the source class, in this case User.
  factory User.fromJson(Map json) => _$UserFromJson(json);

  /// `toJson` is the convention for a class to declare support for serialization
  /// to JSON. The implementation simply calls the private, generated
  /// helper method `_$UserToJson`.
  Map toJson() => _$UserToJson(this);
}

//当然也支持自定义属性名称
@JsonKey(name: 'registration_date_millis')
final int registrationDateMillis;

执行构建命令:

//单次构建
flutter packages pub run build_runner build

//持续构建
flutter packages pub run build_runner watch

使用:

Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap);

String json = jsonEncode(user);

你可能感兴趣的:(Flutter,Flutter,Json,序列化)