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

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

问题描述

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

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])

问题没有出现在结果中我想找到嵌套字段的值.使用 GPath,我可以深入一层并获得 a 的值

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

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

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

推荐答案

基于错误/线程,它会出现支持点属性访问器的一些歧义问题.根据邮件列表线程,评估 queryField 字符串似乎是您最好的选择:

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

Groovy Web 控制台上的脚本

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

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.

否则,您可以拆分字符串并递归地对对象进行属性评估,从而有效地再现 GPath 遍历行为的子集.

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天全站免登陆