fromJson static method

Money fromJson(
  1. dynamic json, {
  2. PrecisionMode? precisionMode,
})

从 JSON 解析(支持恢复精度模式)

Implementation

static Money fromJson(dynamic json, {PrecisionMode? precisionMode}) {
  if (json == null) return zero;

  // 处理 Map 格式(包含精度模式)
  if (json is Map<String, dynamic>) {
    final amount = json['amount'];
    final modeIndex = json['precisionMode'] as int?;
    // 优先使用 JSON 中的精度模式,其次使用传入的,最后默认 round
    final targetMode = modeIndex != null ? PrecisionMode.values[modeIndex] : (precisionMode ?? PrecisionMode.round);

    if (amount is int) {
      return Money.fromCents(amount, precisionMode: targetMode);
    } else if (amount is String) {
      return Money.fromString(amount, precisionMode: targetMode);
    } else {
      throw FormatException("不支持的 JSON amount 类型:${amount.runtimeType}");
    }
  }

  // 兼容旧格式(仅 int 分或 String 元,无精度模式)
  if (json is int) {
    return Money.fromCents(json, precisionMode: precisionMode ?? PrecisionMode.round);
  } else if (json is String) {
    return Money.fromString(json, precisionMode: precisionMode ?? PrecisionMode.round);
  } else {
    throw FormatException("不支持的 JSON 类型:${json.runtimeType}");
  }
}