Way to deep traverse a Groovy object with dot in string using GPath

旧街凉风 提交于 2020-01-11 06:05:49

问题


The situation I have is that I'm querying MongoDB with a string for a field that is more than one level deep in the object hierarchy. This query must be a string. So for example I'm querying for something like this in Groovy:

def queryField = 'a.b.c'  //this is variable and can be different every time
def result = mongodb.collection.findOne([queryField:5])

The problem no arises that in the result I want to find the value of the nested field. With GPath I could go one level deep and get a's value doing this

def aObj = result."a"  //or result["a"]

However I want to go deeper than that by doing something like this:

def queryField = "a.b.c"       //this can change every time and is not always 'a.b.c'
def cObj = result[queryField]  //since field is variable, can't just assume result.a.b.c

This does not work in Groovy right now. There is a bug logged here, but I was wondering if there is a better work around to use for this scenario that is a bit cleaner than me parsing the string by splitting on the dot and then building the object traversal. Note that "a.b.c" is variable and unknown at runtime (e.g. it could be "a.b.d").


回答1:


Based on the bug/thread it would appear there are some ambiguity problems with supporting a dotted property accessor. Based on the mailing list thread it would seem that evaluating the queryField string would be your best bet:

def result = [a: [b: [c: 42]]]
def queryString = 'a.b.c'

def evalResult = Eval.x(result, 'x.' + queryString)
assert evalResult == 42

Script on Groovy Web Console

The mailing list thread is a little old, so there's a new-ish (since at least 1.7.2) Eval class that can help out with running small snippets that don't have a large binding.

Otherwise, you can split the string and recursively do property evaluations on the object, effectively reproducing a subset of GPath traversal behavior.



来源:https://stackoverflow.com/questions/9180039/way-to-deep-traverse-a-groovy-object-with-dot-in-string-using-gpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!