跳到正文
教程首页
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/decoding.dart
/// 健壮的解码层:把"脏 JSON"变成"可诊断的异常"。
///
/// 三个原则:
///   1. 语法错误(FormatException)和结构错误(类型不对)要分开报;
///   2. 错误信息必须带**路径**(`$.items[2].quantity`),否则线上排查无从下手;
///   3. 边界层捕获一切,向上只抛自己的异常类型(不让 TypeError 泄漏给 UI)。
library;

import 'dart:convert';

/// 带路径的解析失败。
class JsonParseException implements Exception {
  JsonParseException(this.path, this.message, [this.cause]);

  /// JSON 路径,如 `$.items[2].quantity`。
  final String path;
  final String message;
  final Object? cause;

  @override
  String toString() => 'JsonParseException($path): $message';
}

// ---------------------------------------------------------------------------
// 基本类型断言:失败时抛出带路径的异常
// ---------------------------------------------------------------------------

Map<String, Object?> expectObject(Object? value, String path) {
  if (value is Map<String, Object?>) return value;
  if (value is Map) {
    // JSON 解码出来永远是 Map<String, dynamic>;这里兼容手工构造的 Map。
    return <String, Object?>{
      for (final MapEntry<Object?, Object?> e in value.entries)
        if (e.key is String) e.key! as String: e.value,
    };
  }
  throw JsonParseException(path, '期望 object,实际是 ${value.runtimeType}');
}

List<Object?> expectList(Object? value, String path) {
  if (value is List<Object?>) return value;
  throw JsonParseException(path, '期望 array,实际是 ${value.runtimeType}');
}

String expectString(Object? value, String path) {
  if (value is String) return value;
  throw JsonParseException(path, '期望 string,实际是 ${value.runtimeType}');
}

/// 整数:接受 `int`,也接受"没有小数部分的 double"(JSON 里 `3.0` 很常见)。
int expectInt(Object? value, String path) {
  if (value is int) return value;
  if (value is double && value == value.truncateToDouble() && value.isFinite) {
    return value.toInt();
  }
  throw JsonParseException(path, '期望整数,实际是 $value (${value.runtimeType})');
}

double expectDouble(Object? value, String path) {
  if (value is num) return value.toDouble();
  throw JsonParseException(path, '期望数字,实际是 ${value.runtimeType}');
}

bool expectBool(Object? value, String path) {
  if (value is bool) return value;
  throw JsonParseException(path, '期望 boolean,实际是 ${value.runtimeType}');
}

/// 可选字段:缺失或 null 都返回 null;存在则必须通过校验。
T? optional<T>(Object? value, String path, T Function(Object? value, String path) convert) =>
    value == null ? null : convert(value, path);

// ---------------------------------------------------------------------------
// 入口:字符串 → 模型
// ---------------------------------------------------------------------------

/// 解码 + 转换,统一把解析错误转成 [JsonParseException]。
T decodeModel<T>(String raw, T Function(Map<String, Object?> json) fromJson) {
  final Object? decoded;
  try {
    decoded = jsonDecode(raw);
  } on FormatException catch (e) {
    // 语法错误:括号不匹配、尾逗号、单引号…… DART 的报错会带 offset。
    throw JsonParseException(r'$', 'JSON 语法错误: ${e.message}', e);
  }

  final Map<String, Object?> root = expectObject(decoded, r'$');
  try {
    return fromJson(root);
  } on JsonParseException {
    rethrow; // 自己抛的,路径已经正确
  } on TypeError catch (e) {
    // 手写模型里 `as String` 之类的强转失败会落到这里(没有路径信息)。
    throw JsonParseException(r'$', '字段类型不匹配: $e', e);
  } on FormatException catch (e) {
    // DateTime.parse 之类会抛 FormatException
    throw JsonParseException(r'$', '字段格式错误: ${e.message}', e);
  }
}

/// 解码数组:`[{...}, {...}]` → `List<T>`。
List<T> decodeList<T>(String raw, T Function(Map<String, Object?> json) fromJson) {
  final Object? decoded;
  try {
    decoded = jsonDecode(raw);
  } on FormatException catch (e) {
    throw JsonParseException(r'$', 'JSON 语法错误: ${e.message}', e);
  }
  final List<Object?> list = expectList(decoded, r'$');
  return <T>[
    for (var i = 0; i < list.length; i++)
      fromJson(expectObject(list[i], '\$[$i]')),
  ];
}

代码构成: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 个用例全绿
查看全部示例