Flutter json_serializable 使用说明

18 min read

添加依赖

name: example
publish_to: none

environment:
  sdk: '>=2.17.0 <3.0.0'

dependencies:
  json_annotation: ^4.4.0

dev_dependencies:
  # Used by tests. Not required to use `json_serializable`.
  _json_serial_shared_test:
    path: ../shared_test
  build_runner: ^2.0.0

  # Used by tests. Not required to use `json_serializable`.
  build_verify: ^3.0.0

  json_serializable: ^6.0.0

  # Not required to use `json_serializable`.
  lints: ^2.0.0
  path: ^1.8.0
  test: ^1.16.0
flutter pub add json_serializable

新建 model

import 'package:json_annotation/json_annotation.dart';

part 'Person.g.dart';

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

生成相关类

flutter packages pub run build_runner build

使用插件生成

  • 安装 Settings/Preferences > Plugins > Marketplace > Search for "FlutterJsonBeanFactory" > Install Plugin
  • 在相应的目录下右键 JsonToDartBeanAction