Flutter之Json序列化

前言

使用 json_annotation 框架实现json字符串序列化和反序列化

框架官方地址:json_serializable

一、引入依赖:在pubspec.yaml中添加

dependencies:
    json_annotation: ^4.8.1


dev_dependencies:
  build_runner: ^2.3.3
  json_serializable: ^6.6.0

二、使用过程

数据源:

{
  "id": 1,
  "name": "John",
  "email": "[email protected]",
  "phone_numbers": [
    {
      "type": "home",
      "number": "1234567890"
    },
    {
      "type": "work",
      "number": "0987654321"
    }
  ]
}

创建数据模型:

// 引入依赖
import 'package:json_annotation/json_annotation.dart';

// 指定此类的代码生成文件(格式:part '类名.g.dart';)
part 'Person.g.dart';

// 添加序列化标注
@JsonSerializable()
class Person {
  int id;
  String name;
  String email;
  // 使用别名
  @JsonKey(name: "phone_numbers")
  List phoneNumbers;

  Person(this.id, this.name, this.email, this.phoneNumbers);
  // 添加反序列化方法(格式:factory 类名.fromJson(Map json) => _$类名FromJson(json);)
  factory Person.fromJson(Map json) => _$PersonFromJson(json);
  // 添加序列化方法(格式:Map toJson() => _$类名ToJson(this);)
  Map toJson() => _$PersonToJson(this);
}

@JsonSerializable()
class PhoneNumber {
  String type;
  String number;

  PhoneNumber(this.type, this.number);
  factory PhoneNumber.fromJson(Map json) => _$PhoneNumberFromJson(json);
  Map toJson() => _$PhoneNumberToJson(this);
}

使用命令生成对应的.g.dart内容

在android studio的Terminal终端使用如下命令:

flutter pub run build_runner build

命令生成过程:

PS D:\AndroidStudioProjects\github_client_app> flutter pub run build_runner build
Deprecated. Use `dart run` instead.
Building package executable... (5.9s)
Built build_runner:build_runner.
[INFO] Generating build script completed, took 252ms
[INFO] Reading cached asset graph completed, took 73ms
[INFO] Checking for updates since last build completed, took 685ms
[INFO] Running build completed, took 19.0s
[INFO] Caching finalized dependency graph completed, took 87ms
[INFO] Succeeded after 19.1s with 602 outputs (606 actions)
PS D:\AndroidStudioProjects\github_client_app> flutter pub run build_runner build
Deprecated. Use `dart run` instead.
[INFO] Generating build script completed, took 252ms
[INFO] Reading cached asset graph completed, took 193ms
[INFO] Checking for updates since last build completed, took 683ms
[INFO] Running build completed, took 10.1s
[INFO] Caching finalized dependency graph completed, took 86ms
[INFO] Succeeded after 10.2s with 189 outputs (193 actions)

查看Person.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'Person.dart';

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

Person _$PersonFromJson(Map json) => Person(
      json['id'] as int,
      json['name'] as String,
      json['email'] as String,
      (json['phone_numbers'] as List)
          .map((e) => PhoneNumber.fromJson(e as Map))
          .toList(),
    );

Map _$PersonToJson(Person instance) => {
      'id': instance.id,
      'name': instance.name,
      'email': instance.email,
      'phone_numbers': instance.phoneNumbers,
    };

PhoneNumber _$PhoneNumberFromJson(Map json) => PhoneNumber(
      json['type'] as String,
      json['number'] as String,
    );

Map _$PhoneNumberToJson(PhoneNumber instance) =>
    {
      'type': instance.type,
      'number': instance.number,
    };

使用示例:

void jsonTest() {
    final json = '''
{
  "id": 1,
  "name": "John",
  "email": "[email protected]",
  "phone_numbers": [
    {
      "type": "home",
      "number": "1234567890"
    },
    {
      "type": "work",
      "number": "0987654321"
    }
  ]
}
''';
    final person = Person.fromJson(jsonDecode(json));
    print("steve:${person.name}");
    final jsonEncoded = jsonEncode(person.toJson());
    print("steve:$jsonEncoded");
  }

打印的日志:

I/flutter ( 1781): steve:John
I/flutter ( 1781): steve:{"id":1,"name":"John","email":"[email protected]","phone_numbers":[{"type":"home","number":"1234567890"},{"type":"work","number":"0987654321"}]}

补充:

jsonKey

  • nullable:默认为true,表示该字段可为null
  • defaultValue:如果源JSON不包含该key或该keyvaluenull,提供一个默认值。
  • name:别名,若为null则默认为字段名。
  • required:默认为false,若为真会检查JSON是否包含该key,若没有则抛出异常(keynull也是有效的)。

生成.g.dart文件

一次性构建
flutter packages pub run build_runner build
删除后重新构建
flutter packages pub run build_runner build --delete-conflicting-outputs
自动为后续创建的数据模型创建
flutter packages pub run build_runner watch

你可能感兴趣的:(Flutter,json,flutter)