示例工程 ch12-json

ch12-json/lib/src/models_generated.dart

dart · 3.1 KB

/// 生成的模型:`json_serializable` 根据注解在编译期(构建期)生成 `_$XxxFromJson`。
///
/// 生成命令:
///   dart run build_runner build --delete-conflicting-outputs
///
/// 生成物在同目录的 `models_generated.g.dart`(必须提交到版本库)。
library;
 
import 'package:json_annotation/json_annotation.dart';
 
import 'models_manual.dart' show Address, Tier;
 
part 'models_generated.g.dart';
 
/// 账号:演示 `fieldRename`、`@JsonKey`、默认值、日期、未知枚举。
@JsonSerializable(fieldRename: FieldRename.snake)
class Account {
  Account({
    required this.id,
    required this.email,
    this.displayName,
    this.balanceCents = 0,
    this.tags = const <String>[],
    this.address,
    this.tier = Tier.free,
    this.createdAt,
    this.isActive = true,
    this.localOnly = '',
  });
 
  factory Account.fromJson(Map<String, Object?> json) => _$AccountFromJson(json);
 
  final String id;
  final String email;
 
  /// 显式重命名优先于 `fieldRename`
  @JsonKey(name: 'display_name')
  final String? displayName;
 
  /// 缺字段时用默认值(生成代码会 `?? 0`)
  @JsonKey(defaultValue: 0)
  final int balanceCents;
 
  final List<String> tags;
 
  /// Address 没有 `@JsonSerializable` 注解(它是手写模型),
  /// 所以生成器不会替它调 toJson;必须显式指定,否则 toJson 后
  /// 里面是一个 Address 对象,`jsonEncode` 会抛 JsonUnsupportedObjectError。
  @JsonKey(toJson: _addressToJson)
  final Address? address;
 
  /// 未知枚举值降级为 free,而不是抛异常
  @JsonKey(unknownEnumValue: Tier.free)
  final Tier tier;
 
  /// 自定义序列化:JSON 里是 ISO-8601 字符串,Dart 里是 DateTime
  @JsonKey(name: 'created_at', fromJson: _dateFromJson, toJson: _dateToJson)
  final DateTime? createdAt;
 
  @JsonKey(name: 'is_active')
  final bool isActive;
 
  /// 只在本机使用、**不参与序列化**的字段(缓存、UI 状态等)。
  ///
  /// `includeFromJson: false, includeToJson: false` 是当前推荐的写法;
  /// 旧写法 `@JsonKey(ignore: true)` 已废弃,但作用相同。
  @JsonKey(includeFromJson: false, includeToJson: false)
  final String localOnly;
 
  Map<String, Object?> toJson() => _$AccountToJson(this);
 
  static Map<String, Object?>? _addressToJson(Address? value) => value?.toJson();
 
  static DateTime? _dateFromJson(Object? value) =>
      value is String ? DateTime.tryParse(value) : null;
 
  static String? _dateToJson(DateTime? value) => value?.toUtc().toIso8601String();
}
 
/// 需要显式序列化嵌套对象时加 `explicitToJson: true`;
/// 否则 `toJson()` 会把嵌套对象原样放进去(再被 jsonEncode 递归处理,通常也能工作)。
@JsonSerializable(explicitToJson: true)
class Payload {
  Payload({required this.account, required this.extra});
 
  factory Payload.fromJson(Map<String, Object?> json) => _$PayloadFromJson(json);
 
  final Account account;
 
  /// 任意键值对:`Object?` 在生成代码里会原样传递,不会被强转。
  final Map<String, Object?> extra;
 
  Map<String, Object?> toJson() => _$PayloadToJson(this);
}