jsonUtils.dart 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import 'dart:convert';
  2. class JsonUtils {
  3. static String encodeJson(Object? value, {
  4. Object? Function(dynamic object)? toEncodable,
  5. }) {
  6. return json.encode(value, toEncodable: toEncodable);
  7. }
  8. static dynamic decodeJson(String source, {
  9. Object? Function(Object? key, Object? value)? reviver,
  10. }) {
  11. return json.decode(source, reviver: reviver);
  12. }
  13. static String getString(Map? map, String key, {String defaultValue = ''}) {
  14. if (map == null || !map.containsKey(key)) return defaultValue;
  15. final value = map[key];
  16. if (value == null) return defaultValue;
  17. return value.toString();
  18. }
  19. static String? tryGetString(Map? map, String key) {
  20. if (map == null || !map.containsKey(key)) return null;
  21. final value = map[key];
  22. if (value == null) return null;
  23. return value.toString();
  24. }
  25. static int getInt(Map? map, String key, {int defaultValue = 0}) {
  26. if (map == null || !map.containsKey(key)) return defaultValue;
  27. final value = map[key];
  28. if (value == null) return defaultValue;
  29. if (value is int) return value;
  30. return int.tryParse(value.toString()) ?? defaultValue;
  31. }
  32. static int? tryGetInt(Map? map, String key) {
  33. if (map == null || !map.containsKey(key)) return null;
  34. final value = map[key];
  35. if (value == null) return null;
  36. if (value is int) return value;
  37. return int.tryParse(value.toString());
  38. }
  39. static DateTime getDateTime(Map? map, String key) {
  40. DateTime defaultValue = DateTime.now();
  41. if (map == null || !map.containsKey(key)) return defaultValue;
  42. final value = map[key];
  43. if (value == null) return defaultValue;
  44. if (value is int) return DateTime.fromMillisecondsSinceEpoch(value);
  45. final dateTime = DateTime.tryParse(value.toString());
  46. return dateTime ?? defaultValue;
  47. }
  48. static DateTime? tryGetDateTime(Map? map, String key) {
  49. DateTime? defaultValue;
  50. if (map == null || !map.containsKey(key)) return defaultValue;
  51. final value = map[key];
  52. if (value == null) return defaultValue;
  53. if (value is int) return DateTime.fromMillisecondsSinceEpoch(value);
  54. final dateTime = DateTime.tryParse(value.toString());
  55. return dateTime ?? defaultValue;
  56. }
  57. }