使用GPath在字符串中深入遍历Groovy对象的方法 [英] Way to deep traverse a Groovy object with dot in string using GPath

查看:578
本文介绍了使用GPath在字符串中深入遍历Groovy对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是,我正在使用字符串查询MongoDB,查找对象层次结构中多于一个级别的字段。这个查询必须是一个字符串。例如,我在Groovy中查询类似这样的内容:

  def queryField ='abc'//这是可变的并且可以每次都不同
def result = mongodb.collection.findOne([queryField:5])

问题没有出现,结果我想找到嵌套字段的值。通过GPath,我可以深入一层,并获得价值。

  def aObj = result。a//或结果[a] 

然而,我想要做的更深入: p>

  def queryField =abc//这可以每次都改变,并不总是'abc'
def cObj = result [queryField] //因为field是变量,不能只是假设result.abc

现在不在Groovy中工作。 此处有一个错误,但我想知道是否有更好的解决方法在这个场景中使用它比我稍微清晰一些,通过分割点然后构建对象遍历来解析字符串。请注意,a.b.c在运行时是可变的和未知的(例如,它可能是a.b.d)。

解决方案

基于bug /线程,它会出现支持虚线属性访问器的一些模糊问题。根据邮件列表线程,似乎评估queryField字符串将是您最好的选择:

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

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

Groovy Web控制台上的脚本



邮件列表线程有点旧,所以有一个新的ish至少1.7.2)Eval类可以帮助运行没有大绑定的小片段。



否则,您可以拆分字符串并递归执行属性对物体进行评估,有效地再现GPath遍历行为的一个子集。

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").

解决方案

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.

这篇关于使用GPath在字符串中深入遍历Groovy对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆