示例工程 ch12-json

ch12-json/lib/src/decoding.dart

dart · 4.3 KB

/// 健壮的解码层:把"脏 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]')),
  ];
}