示例工程 ch12-json

ch12-json/lib/src/models_manual.dart

dart · 5.0 KB

/// 手写模型:`fromJson` / `toJson` 完全靠自己,适合理解机制、或结构极简的场景。
///
/// 对照 Go:struct tag + `encoding/json` 自动映射;
/// 对照 C:cJSON 手动 `cJSON_GetObjectItem` 逐字段取,还要记得 `cJSON_Delete`。
/// Dart 里没有编译期反射,所以要么手写,要么用 `json_serializable` 生成。
library;
 
import 'package:json_annotation/json_annotation.dart';
 
/// 地址:嵌套对象。
class Address {
  const Address({required this.city, this.street, this.zipCode});
 
  factory Address.fromJson(Map<String, Object?> json) => Address(
        // `as String` 是强转:类型不对会抛 TypeError(ch03 的 null 安全 + 类型系统)
        city: json['city'] as String,
        street: json['street'] as String?,
        zipCode: json['zip'] as String?,
      );
 
  final String city;
  final String? street;
  final String? zipCode;
 
  Map<String, Object?> toJson() => <String, Object?>{
        'city': city,
        // 可空字段:业务上决定"省略"还是"写 null"
        if (street != null) 'street': street,
        'zip': zipCode,
      };
 
  @override
  bool operator ==(Object other) =>
      other is Address && other.city == city && other.street == street && other.zipCode == zipCode;
 
  @override
  int get hashCode => Object.hash(city, street, zipCode);
}
 
/// 会员等级。
///
/// 用 `@JsonValue` 显式声明线上的字符串:枚举名一旦改(重构、拼写修正),
/// 协议不变;json_serializable 也能直接识别。
/// 注意枚举必须是"纯枚举"(没有字段),否则 json_serializable 无法生成转换代码。
enum Tier {
  @JsonValue('free')
  free,
  @JsonValue('pro')
  pro,
}
 
/// 线上字符串 → 枚举。未知值降级为 free:服务端加了新等级,老客户端也不该崩。
Tier tierFromWire(Object? value) =>
    Tier.values.firstWhere((Tier t) => tierToWire(t) == value, orElse: () => Tier.free);
 
/// 枚举 → 线上字符串。
String tierToWire(Tier tier) => switch (tier) {
      Tier.free => 'free',
      Tier.pro => 'pro',
    };
 
/// 用户:手写序列化的完整示例。
class User {
  const User({
    required this.id,
    required this.email,
    this.name,
    this.tier = Tier.free,
    this.tags = const <String>[],
    this.address,
    this.createdAt,
  });
 
  factory User.fromJson(Map<String, Object?> json) {
    final Object? rawTags = json['tags'];
    return User(
      id: json['id'] as String,
      email: json['email'] as String,
      name: json['name'] as String?,
      tier: tierFromWire(json['tier']),
      // 列表要逐个元素校验类型,不能直接 `as List<String>`
      tags: rawTags is List<Object?> ? rawTags.whereType<String>().toList() : const <String>[],
      // 嵌套对象:先判类型再递归
      address: json['address'] is Map<String, Object?>
          ? Address.fromJson(json['address']! as Map<String, Object?>)
          : null,
      createdAt: _parseDate(json['created_at']),
    );
  }
 
  final String id;
  final String email;
  final String? name;
  final Tier tier;
  final List<String> tags;
  final Address? address;
  final DateTime? createdAt;
 
  /// 计算属性不参与序列化(它不在 toJson 里)。
  String get displayName => name ?? email.split('@').first;
 
  Map<String, Object?> toJson() => <String, Object?>{
        'id': id,
        'email': email,
        'name': name,
        'tier': tierToWire(tier),
        'tags': tags,
        'address': address?.toJson(),
        'created_at': createdAt?.toUtc().toIso8601String(),
      };
 
  static DateTime? _parseDate(Object? value) =>
      value is String ? DateTime.tryParse(value) : null;
}
 
/// 订单:列表 + 嵌套 + 计算值。
class OrderItem {
  const OrderItem({required this.sku, required this.quantity, required this.unitCents});
 
  factory OrderItem.fromJson(Map<String, Object?> json) => OrderItem(
        sku: json['sku'] as String,
        quantity: (json['quantity'] as num).toInt(),
        unitCents: (json['unit_cents'] as num).toInt(),
      );
 
  final String sku;
  final int quantity;
  final int unitCents;
 
  int get subtotalCents => quantity * unitCents;
 
  Map<String, Object?> toJson() => <String, Object?>{
        'sku': sku,
        'quantity': quantity,
        'unit_cents': unitCents,
      };
}
 
class Order {
  const Order({required this.id, required this.items, this.note});
 
  factory Order.fromJson(Map<String, Object?> json) => Order(
        id: json['id'] as String,
        items: <OrderItem>[
          for (final Object? raw in (json['items'] as List<Object?>? ?? const <Object?>[]))
            if (raw is Map<String, Object?>) OrderItem.fromJson(raw),
        ],
        note: json['note'] as String?,
      );
 
  final String id;
  final List<OrderItem> items;
  final String? note;
 
  int get totalCents => items.fold(0, (int sum, OrderItem i) => sum + i.subtotalCents);
 
  Map<String, Object?> toJson() => <String, Object?>{
        'id': id,
        'items': <Map<String, Object?>>[for (final OrderItem i in items) i.toJson()],
        'note': note,
      };
}