如何在Groovy中使用字符串插值从带点表示法的嵌套地图的属性中获取值 [英] How to get a value from a property of a nested map with dot notation in Groovy using string interpolation
问题描述
我从参数中收到一个点号表示的字符串,例如"attr1.attr2.attr3"
.我有一个数据类型为 LinkedHashMap< String,Object>的对象.mapObject
.它具有可以通过这种方式访问的值: mapObject.attr1.attr2.attr3
.
I receive a dot notated string from parameter, e.g. "attr1.attr2.attr3"
.
I have an object of data type LinkedHashMap<String, Object> mapObject
.
It has a value that can be accessed this way: mapObject.attr1.attr2.attr3
.
当我尝试以这种方式访问字段: mapObject." $ {attr1.attr2.attr3}
时,由于Groovy的翻译,我收到了 MissingPropertyException
.作为字符串: mapObject.""attr1.attr2.attr3"
,显然该属性不存在.我设法使用 Eval.java类Eval.x()
方法来解决此问题: Eval.x(mapObject,"x.$ {attr1.attr2.attr3}";)
,但这对于蜗牛来说也太慢了.
When I try to access the field in this way: mapObject."${attr1.attr2.attr3}
, I receive a MissingPropertyException
, as groovy translates it as a String: mapObject."attr1.attr2.attr3"
and that property, obviously, does not exist.
I have managed to solve it using the Eval.java class Eval.x()
method this way: Eval.x(mapObject,"x.${attr1.attr2.attr3}")
, but this is too slow even for a snail.
有没有一种方法可以让我只知道点标记的路径来获取地图的嵌套属性的值?
Does there exist a way where I can get the value of a nested property of a map knowing only the dot notated path?
这是我的代码:
def superCoolMethod(String dotNotatedPath, LinkedHashMap<String, Object> MapObject){
def valueINeedToGetFromTheMapObject = MapObject."${dotNotatedPath}"
// Other stuff unimportant for this question.
推荐答案
您可以在.
上分割路径(用正则表达式引用),然后减少在路径上使用您的数据.例如
You can split the path on .
(quote it for the regexp) and then reduce
over the path using your data. E.g.
def data = [a: [b: [c: 42]]]
def path = "a.b.c"
println path.split(/\./).inject(data){ m, p -> m?.getAt(p) }
// → 42
这篇关于如何在Groovy中使用字符串插值从带点表示法的嵌套地图的属性中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!