Ver código fonte

remove null value when decode

JamesZhang 1 mês atrás
pai
commit
1813fdfc4b
1 arquivos alterados com 21 adições e 1 exclusões
  1. 21 1
      lib/utils/jsonUtils.dart

+ 21 - 1
lib/utils/jsonUtils.dart

@@ -14,10 +14,30 @@ class JsonUtils {
   static dynamic decodeJson(String source, {
     Object? Function(Object? key, Object? value)? reviver,
   }) {
-    return json.decode(source, reviver: reviver);
+    return removeNullValues(json.decode(source, reviver: reviver));
   }
 
 
+  /// 递归移除 JSON 对象中的 null 字段,保持数组顺序并保留数组中的 null。
+  /// 顶层 null 会原样返回,由调用方决定其业务含义。
+  static dynamic removeNullValues(dynamic value) {
+    if (value is Map) {
+      final Map result = value is Map<String, dynamic>
+          ? <String, dynamic>{}
+          : <dynamic, dynamic>{};
+      value.forEach((key, nestedValue) {
+        if (nestedValue != null) {
+          result[key] = removeNullValues(nestedValue);
+        }
+      });
+      return result;
+    }
+    if (value is List) {
+      return value.map(removeNullValues).toList();
+    }
+    return value;
+  }
+
   static String getString(Map? map, String key, {String defaultValue = ''}) {
     if (map == null || !map.containsKey(key)) return defaultValue;
     final value = map[key];