跳到正文
教程首页
DartCH 12ch12_json

ch12-json

JSON 编解码:dart:convert、json_serializable、健壮错误处理。完整工程共 12 个文件,其中 12 个文本源文件可在下面在线阅读。

12

在线文本文件

1,502

源码行数

dart / yaml / text

语言

19 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextyaml

12 text files · 1,502 lines

dartlib/src/models_manual.dart
/// 手写模型:`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,
      };
}

代码构成:dart 33 KB · text 15 KB · yaml 471 B

本地运行

zip → 解压 → 执行
$cd examples/ch12-json && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze 0 告警、dart test 24 个用例全绿
查看全部示例