如何在Groovy JSONSlurper中获取动态键的值? [英] How to get a value of a dynamic key in Groovy JSONSlurper?
问题描述
变量resp
包含以下JSON响应-
The variable resp
contains below JSON response -
{"name":"sample","address":{"country":"IN","state":"TN","city":"Chennai"}}
我计划使用param1
变量从JSON响应中获取所需的密钥,但是我无法获得预期的结果.
I have planned using param1
variable to get the required key from JSON response, but I'm unable to get my expected results.
我正在传递param1
字段,例如-address.state
I'm passing the param1
field like - address.state
def actValToGet(param1){
JsonSlurper slurper = new JsonSlurper();
def values = slurper.parseText(resp)
return values.param1 //values.address.state
}
我在这里获得NULL
值-> values.param1
I'm getting NULL
value here -> values.param1
任何人都可以帮助我.我是Groovy的新手.
Can anyone please help me. I'm new to Groovy.
推荐答案
从JsonSlurper
返回的地图是嵌套的,而不是平坦的.换句话说,它是一个地图地图(完全反映了已解析的Json文本).第一个映射中的键是name
和address
. name
的值是一个字符串; address
的值是另一个映射,还有三个键.
The map returned from the JsonSlurper
is nested rather than than flat. In other words, it is a map of maps (exactly mirroring the Json text which was parsed). The keys in the first map are name
and address
. The value of name
is a String; the value of address
is another map, with three more keys.
为了解析出嵌套键的值,您必须遍历每一层.这是一个程序解决方案,用于显示正在发生的事情.
In order to parse out the value of a nested key, you must iterate through each layer. Here is a procedural solution to show what's happening.
class Main {
static void main(String... args) {
def resp = '{"name":"sample","address":{"country":"IN","state":"TN","city":"Chennai"}}'
println actValToGet(resp, 'address.state')
}
static actValToGet(String resp, String params){
JsonSlurper slurper = new JsonSlurper()
def values = slurper.parseText(resp)
def keys = params.split(/\./)
def output = values
keys.each { output = output.get(it) }
return output
}
}
更实用的方法可能是将可变的output
变量替换为inject()
方法.
A more functional approach might replace the mutable output
variable with the inject()
method.
static actValToGet2(String resp, String params){
JsonSlurper slurper = new JsonSlurper()
def values = slurper.parseText(resp)
def keys = params.split(/\./)
return keys.inject(values) { map, key -> map.get(key) }
}
为了证明Groovy的简洁性,我们可以一行完成全部工作.
And just to prove how concise Groovy can be, we can do it all in one line.
static actValToGet3(String resp, String params){
params.split(/\./).inject(new JsonSlurper().parseText(resp)) { map, key -> map[key] }
}
您可能想通过parseText()
方法在values
输出上设置调试点,以了解其返回的内容.
You may want to set a debug point on the values
output by the parseText()
method to understand what it's returning.
这篇关于如何在Groovy JSONSlurper中获取动态键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!