【问题标题】:How to access hashMaps in grails如何在 grails 中访问 hashMaps
【发布时间】:2023-03-16 14:33:01
【问题描述】:

我有一个有趣的问题:我无法访问我的 hashmap 键。

我有以下哈希图:

{a=Retrieve User Account call failed, b=This user has multiple accounts}

当我执行以下任何操作时,我得到空白变量:

"${myMap.get('a')}"
"${myMap['a']}"
"${myMap.a}"

我从以下位置得到错误值:

"${myMap.containsKey('a')}"
"${myMap.keySet().contains('a')}"

但是当我这样做时我会得到真实的:

"${myMap.keySet()[1] == 'a'}"

有什么问题?以及如何在 hashmap 键或 keySet 上调用 contains 以查明 'a' 是否在散列/列表中?

如果有帮助的话,我正在为 Groovy/Grails Tool Suite 和 grails 2.4.1 使用 groovy 2.3.0-rc-2 插件

【问题讨论】:

  • 这不是一个有效的哈希图,看起来像是某种真正损坏的 JSON。
  • 您所描述的实际上是不可能的,但考虑到您在示例中表示地图的方式,很难说它是否甚至是地图。除此之外,如果您有一个包含键“a”的 Map,并且与该键关联的值是字符串“检索用户帐户调用失败”,那么myMap.get('a')myMap['a']myMap.a 都将评估到字符串“检索用户帐户调用失败”。
  • @JoshuaMoore 它不是损坏的 JSON,它是 java Map 的标准 toString()
  • @IanRoberts 啊,是的!确实如此!
  • 这里的ab 是什么?它们肯定是字符串而不是(比如说)GStrings?地图究竟是如何初始化的?

标签: grails groovy hashmap


【解决方案1】:

这可能是一个重复的问题,但无论如何我都会回答它。您在 Groovy 中的语法有点偏离。

请看这里:http://groovy.codehaus.org/Collections

他们的例子:

def map = [name:"Gromit", likes:"cheese", id:1234]
assert map.get("name") == "Gromit"
assert map.get("id") == 1234
assert map["name"] == "Gromit"
assert map['id'] == 1234
assert map instanceof java.util.Map

def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.put("foo", 5)
assert emptyMap.size() == 1
assert emptyMap.get("foo") == 5

你的地图:

def map = [a:"Retrieve User Account call failed", 
    b:"This user has multiple accounts"]

assert map.get("a") == "Retrieve User Account call failed"
// also
assert map.a == "Retrieve User Account call failed"

【讨论】:

  • 您在那里的单个等号断言是无效的。你需要双等号。
猜你喜欢
  • 2011-10-31
  • 2012-01-01
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 2010-10-14
  • 2019-07-11
  • 2019-02-21
  • 1970-01-01
相关资源
最近更新 更多