简体   繁体   English

使用映射将Grails数据绑定到命令对象-将密钥转换为数字

[英]Grails data binding to command object with maps - convert key to number

I have a Grails command object with a list of maps. 我有一个带有地图列表的Grails命令对象。 The map key is intended to be a numeric domain object ID. 映射键旨在作为数字域对象ID。

class MyCommand {
  def grid = [].withDefault { [:] }
}

Data binding to the list/map is working in general because of the dynamic list expansion. 由于动态列表扩展,通常将数据绑定到列表/映射上。

However, in the POST, the map keys are being bound as Strings and I want them to be Longs, as they are when the form is initially populated. 但是,在POST中,映射键被绑定为字符串,我希望它们为Longs,就像最初填充表单时那样。 I want foo[123] in my map, not foo['123'] . 我要在地图中添加foo[123] ,而不是foo['123']

Alternatively I would be satisfied if the [] operators found the correct value given a numeric ID key to look up. 或者,如果[]运算符找到了给定数字ID键查找的正确值,我将感到满意。 In other words, if I could get foo[123] to return the same value as foo['123'] , that would work too. 换句话说,如果我可以让foo[123]返回与foo['123']相同的值,那也将起作用。

Any way to get this to work the way I want to? 有什么办法可以按照我想要的方式工作吗? Maybe strongly type the map? 也许强烈输入地图?

Or a better approach? 还是更好的方法?

You can inject the property into the map to convert a String key to Long . 您可以inject属性注入到映射中,以将String键转换为Long For example: 例如:

def myMap = [:] << ['1': "name"] << ['Test': "bobo"]
def result = myMap.inject([:]){map, v ->
   def newKey = v.key.isNumber() ? v.key.toLong() : v.key
   map[newKey] = v.value
   map
}

assert myMap['1'] == 'name'
assert result[1L] == 'name'
assert result['Test'] == 'bobo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM