How to get a value of a dynamic key in Groovy JSONSlurper?

只愿长相守 提交于 2020-03-04 18:03:13

问题


The variable resp contains below JSON response -

{"name":"sample","address":{"country":"IN","state":"TN","city":"Chennai"}} 

I have planned using param1 variable to get the required key from JSON response, but I'm unable to get my expected results.

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
}

I'm getting NULL value here -> values.param1

Can anyone please help me. I'm new to Groovy.


回答1:


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
    }
}

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

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

You may want to set a debug point on the values output by the parseText() method to understand what it's returning.



来源:https://stackoverflow.com/questions/58052344/how-to-get-a-value-of-a-dynamic-key-in-groovy-jsonslurper

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