json - 在 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"]。有没有办法将这些键保存在变量中,以便我可以添加或删除它们以访问不同的级别?
提前致谢?
解决方案
您可以实现一个函数,该函数接受一个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
.
推荐阅读
- php - 单击禁用按钮时禁用数据行
- php - 从 issuu.com 站点检索文档列表而不使用限制
- java - 如何使用 Lombok 访问 getter 和 setter 方法?
- c++ - 使用继承的 QGraphicsScene 时的 SIGSEGV
- c# - 针对登录用户,为多个数据库架构动态创建 DbContext
- selenium - Selenium 测试用例是宏吗?
- wpf - 页面只能有 Frame 作为父级,不能有 Window
- javascript - Formdata 对象正在转换为 ASP.NET MVC 中的查询字符串
- java - 如何将对象类列表添加到arraylist?
- javascript - 使用带有 ASP.NET Core 的自定义 html 属性对数据表中的列进行排序