James 2 tháng trước cách đây
mục cha
commit
2a627a3261
1 tập tin đã thay đổi với 349 bổ sung0 xóa
  1. 349 0
      lib/utils/jsonUtils.dart

+ 349 - 0
lib/utils/jsonUtils.dart

@@ -82,4 +82,353 @@ class JsonUtils {
     return dateTime ?? defaultValue;
   }
 
+
+
+  /// ==================== Enum 通用转换方法 ====================
+
+  /// 将枚举值转换为字符串
+  /// 示例:
+  /// enum Status { active, inactive }
+  /// String json = JsonUtils.enumToJson(Status.active); // "active"
+  ///
+
+  static String enumToJson<T extends Enum>(T value) {
+    return value.name;
+  }
+
+  /// 将字符串转换为枚举值(带默认值)
+  ///
+  /// 参数:
+  /// - [values]: 枚举的所有值,通过 EnumType.values 传入
+  /// - [name]: 要转换的字符串
+  /// - [defaultValue]: 解析失败时的默认值
+  /// 示例:
+  /// enum ApiVersion { v1, v2, v3 }
+  /// var version = JsonUtils.jsonToEnum(
+  ///   ApiVersion.values,
+  ///   'v2',
+  ///   defaultValue: ApiVersion.v1,
+  /// );
+  ///
+  static T jsonToEnum<T extends Enum>(List<T> values, String? name, {
+    required T defaultValue,
+  }) {
+    if (name == null || name.isEmpty) {
+      return defaultValue;
+    }
+
+    return values.firstWhere(
+          (e) => e.name.toLowerCase() == name.toLowerCase(),
+      orElse: () => defaultValue,
+    );
+  }
+
+  /// 将字符串转换为可空的枚举值(解析失败返回 null)
+  /// 示例:
+  /// enum Priority { low, medium, high } /// var priority = JsonUtils.tryJsonToEnum(Priority.values, 'medium'); ///
+  static T? tryJsonToEnum<T extends Enum>(List<T> values, String? name) {
+    if (name == null || name.isEmpty) {
+      return null;
+    }
+
+    return values.firstWhere(
+          (e) => e.name.toLowerCase() == name.toLowerCase(),
+      orElse: () => throw StateError('No matching enum value'),
+    );
+  }
+
+  /// 从 Map 中安全地获取枚举值(带默认值)
+  /// 示例:
+  /// var apiVersion = JsonUtils.getEnumFromMap(
+  ///   map,
+  ///   'api_version',
+  ///   ApiVersion.values,
+  ///   defaultValue: ApiVersion.v1,
+  /// );
+  ///
+  static T getEnumFromMap<T extends Enum>(
+      Map? map,
+      String key,
+      List<T> values, {
+        required T defaultValue,
+      }) {
+    if (map == null || !map.containsKey(key)) {
+      return defaultValue;
+    }
+
+    final name = map[key]?.toString();
+    return jsonToEnum(values, name, defaultValue: defaultValue);
+  }
+
+  /// 从 Map 中安全地获取可空的枚举值
+  /// 示例:
+  /// var priority = JsonUtils.tryGetEnumFromMap(
+  ///   map,
+  ///   'priority',
+  ///   Priority.values,
+  /// );
+  ///
+  static T? tryGetEnumFromMap<T extends Enum>(
+      Map? map,
+      String key,
+      List<T> values,
+      ) {
+    if (map == null || !map.containsKey(key)) {
+      return null;
+    }
+
+    final name = map[key]?.toString();
+    return tryJsonToEnum(values, name);
+  }
+
+  /// 将枚举值按索引转换为整数
+  /// 示例:
+  /// int index = JsonUtils.enumToInt(Status.active); // 0
+  ///
+  static int enumToInt<T extends Enum>(T value) {
+    return value.index;
+  }
+
+  /// 将整数转换为枚举值(带默认值)
+  /// 示例:
+  /// var status = JsonUtils.intToEnum(
+  ///   Status.values,
+  ///   1,
+  ///   defaultValue: Status.inactive,
+  /// );
+  ///
+  static T intToEnum<T extends Enum>(
+      List<T> values,
+      int? index, {
+        required T defaultValue,
+      }) {
+    if (index == null || index < 0 || index >= values.length) {
+      return defaultValue;
+    }
+
+    return values.elementAt(index);
+  }
+
+  /// 从 Map 中安全地获取枚举值(通过整数索引)
+  /// 示例:
+  /// var status = JsonUtils.getEnumFromMapByInt(
+  ///   map,
+  ///   'status_index',
+  ///   Status.values,
+  ///   defaultValue: Status.inactive,
+  /// );
+  ///
+  static T getEnumFromMapByInt<T extends Enum>(
+      Map? map,
+      String key,
+      List<T> values, {
+        required T defaultValue,
+      }) {
+    if (map == null || !map.containsKey(key)) {
+      return defaultValue;
+    }
+
+    final index = getInt(map, key, defaultValue: -1);
+    return intToEnum(values, index, defaultValue: defaultValue);
+  }
+
+
+
+
+
+  /// ==================== DateTime 转换 ====================
+
+  /// int timestamp = JsonUtils.dateTimeToTimestamp(DateTime.now());
+  /// // 例如: 1712134567890
+  ///
+  static int dateTimeToTimestamp(DateTime dateTime) {
+    return dateTime.millisecondsSinceEpoch;
+  }
+
+  /// 将毫秒时间戳转换为 DateTime
+  ///
+  /// 参数:
+  /// - [timestamp]: 毫秒时间戳
+  ///
+  /// 示例:
+  /// DateTime date = JsonUtils.timestampToDateTime(1712134567890);
+  ///
+  static DateTime timestampToDateTime(int timestamp) {
+    return DateTime.fromMillisecondsSinceEpoch(timestamp);
+  }
+
+  /// 将 DateTime 转换为秒时间戳(整数)
+  ///
+  /// 示例:
+  ///
+  /// int timestamp = JsonUtils.dateTimeToTimestampSeconds(DateTime.now());
+  /// // 例如: 1712134567
+  ///
+  static int dateTimeToTimestampSeconds(DateTime dateTime) {
+    return dateTime.millisecondsSinceEpoch ~/ 1000;
+  }
+
+  /// 将秒时间戳转换为 DateTime
+  ///
+  /// 参数:
+  /// - [timestamp]: 秒时间戳
+  ///
+  /// 示例:
+  ///
+  /// DateTime date = JsonUtils.timestampSecondsToDateTime(1712134567);
+  ///
+  static DateTime timestampSecondsToDateTime(int timestamp) {
+    return DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
+  }
+
+  /// 将 DateTime 转换为 ISO 8601 格式的字符串
+  ///
+  /// 示例:
+  ///
+  /// String iso = JsonUtils.dateTimeToIsoString(DateTime.now());
+  /// // 例如: "2024-04-03T10:30:00.000Z"
+  ///
+  static String dateTimeToIsoString(DateTime dateTime) {
+    return dateTime.toIso8601String();
+  }
+
+  /// 将 ISO 8601 格式的字符串转换为 DateTime
+  ///
+  /// 参数:
+  /// - [isoString]: ISO 8601 格式的时间字符串
+  /// - [defaultValue]: 解析失败时的默认值
+  ///
+  /// 示例:
+  /// DateTime date = JsonUtils.isoStringToDateTime("2024-04-03T10:30:00.000Z");
+  ///
+  static DateTime isoStringToDateTime(
+      String? isoString, {
+        DateTime? defaultValue,
+      }) {
+    if (isoString == null || isoString.isEmpty) {
+      return defaultValue ?? DateTime.now();
+    }
+
+    final dateTime = DateTime.tryParse(isoString);
+    return dateTime ?? (defaultValue ?? DateTime.now());
+  }
+
+  /// 将可空的 ISO 8601 字符串转换为可空的 DateTime
+  /// 示例:
+  /// DateTime? date = JsonUtils.tryIsoStringToDateTime("2024-04-03T10:30:00.000Z");
+  ///
+  static DateTime? tryIsoStringToDateTime(String? isoString) {
+    if (isoString == null || isoString.isEmpty) {
+      return null;
+    }
+
+    return DateTime.tryParse(isoString);
+  }
+
+
+  /// 从 Map 中安全地获取时间戳并转换为 DateTime(带默认值)
+  ///
+  /// 参数:
+  /// - [map]: 数据 Map
+  /// - [key]: 时间戳字段的 key
+  /// - [defaultValue]: 解析失败时的默认值
+  /// - [isSeconds]: 是否为秒时间戳(默认为 false,即毫秒时间戳)
+  ///
+  /// 示例:
+  /// DateTime createTime = JsonUtils.getDateTimeFromMap( /// map, /// 'create_time', /// defaultValue: DateTime.now(), /// ); ///
+  static DateTime getDateTimeFromMap(
+      Map? map,
+      String key, {
+        DateTime? defaultValue,
+        bool isSeconds = false,
+      }) {
+    if (map == null || !map.containsKey(key)) {
+      return defaultValue ?? DateTime.now();
+    }
+
+    final value = map[key];
+    if (value == null) {
+      return defaultValue ?? DateTime.now();
+    }
+
+    // 如果已经是 DateTime 类型,直接返回
+    if (value is DateTime) {
+      return value;
+    }
+
+    // 尝试解析为整数时间戳
+    int timestamp;
+    if (value is int) {
+      timestamp = value;
+    } else if (value is String) {
+      final parsed = int.tryParse(value);
+      if (parsed == null) {
+        // 如果不是数字,尝试作为 ISO 字符串解析
+        return isoStringToDateTime(value, defaultValue: defaultValue);
+      }
+      timestamp = parsed;
+    } else {
+      return defaultValue ?? DateTime.now();
+    }
+
+    // 根据时间戳类型转换
+    if (isSeconds) {
+      return timestampSecondsToDateTime(timestamp);
+    } else {
+      return timestampToDateTime(timestamp);
+    }
+  }
+
+  /// 从 Map 中安全地获取时间戳并转换为可空的 DateTime
+  /// 示例:
+  /// DateTime? updateTime = JsonUtils.tryGetDateTimeFromMap(map, 'update_time'); ///
+  static DateTime? tryGetDateTimeFromMap(
+      Map? map,
+      String key, {
+        bool isSeconds = false,
+      }) {
+    if (map == null || !map.containsKey(key)) {
+      return null;
+    }
+
+    final value = map[key];
+    if (value == null) {
+      return null;
+    }
+
+    // 如果已经是 DateTime 类型,直接返回
+    if (value is DateTime) {
+      return value;
+    }
+
+    // 尝试解析为整数时间戳
+    int timestamp;
+    if (value is int) {
+      timestamp = value;
+    } else if (value is String) {
+      final parsed = int.tryParse(value);
+      if (parsed == null) {
+        // 如果不是数字,尝试作为 ISO 字符串解析
+        return tryIsoStringToDateTime(value);
+      }
+      timestamp = parsed;
+    } else {
+      return null;
+    }
+
+    // 根据时间戳类型转换
+    if (isSeconds) {
+      return timestampSecondsToDateTime(timestamp);
+    } else {
+      return timestampToDateTime(timestamp);
+    }
+  }
+
+
 }
+
+
+
+
+
+