首页 > 解决方案 > 在 dart 中使用嵌套哈希映射时,如何跟踪一系列键以获取当前嵌套映射?

问题描述

我从 api 接收 JSON。此 JSON 控制用户的一些对话框。例如

{
   "text":"Are you experiecing issues?",
   "true":{
      "text":"Are you using linux?",
      "false":{
         "text":"maybe you should use linux",
         "none":"none"
      }
   }
}

要访问最终的 json,它的一系列键将是 json["true"]["false"]。有没有办法将这些键保存在变量中,以便我可以添加或删除它们以访问不同的级别?

提前致谢?

标签: jsondart

解决方案


您可以实现一个函数,该函数接受一个List键并执行重复查找,直到它用完键或直到它停止查找嵌套Map的 s:

Object? nestedLookup(Map<Object, Object?> map, List<Object> keys) {
  Object? value = map;
  int currentKeyIndex = 0;
  while (currentKeyIndex < keys.length && value is Map) {
    value = value[keys[currentKeyIndex++]];
  }
  
  if (value != null && currentKeyIndex < keys.length) {
    // We have more keys than nested Maps.
    throw ArgumentError('Leftover keys: ${keys.sublist(currentKeyIndex)}');
  }
  return value;
}

请注意,在上述实现中,如果您提供的键太少,您将得到一个嵌套的Map. 如果您提供不存在的键,您将返回null,并且如果您提供一个键来对不是 a 的东西执行查找Map,它将抛出一个ArgumentError.


推荐阅读