简体   繁体   English

Groovy脚本json响应长度

[英]Groovy script json response length

I need to find json response length. 我需要找到json响应长度。 Sample response looks like below: 样本响应如下所示:

{ 
    "resource": {
        "name":"aaaaaaaaaaa",
        "emailid":"bbbbbbbbb"
    }
}

As two parameters are present in resource. 由于资源中存在两个参数。 So, i should have got response as 2. Please let me know hoe i can find json length as 2 因此,我应该得到2的响应。请让我知道,我可以找到json的长度为2

This is the working solution, try this 这是有效的解决方案,请尝试此

import groovy.json.JsonSlurper // import this class

 def jsonText = '''{
                "resource": {
                "name":"aaaaaaaaaaa",
                "emailid":"bbbbbbbbb"
                }
                }'''
 def json = new JsonSlurper().parseText(jsonText)
 println "Json length---------->"+json.resource.size()

If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following, 如果您具有JSON对象,则无需将JSON字符串解析为json,您可以直接执行以下操作:

println jsonObject.resource.size() // Here resource is the key(sub node) inside your json

If you want to get the length of parent JSON key, just do as follows, 如果要获取父JSON密钥的长度,请执行以下操作,

 println jsonObject.size()

Based on your question, it appears that you would like to know the count of properties within a JSON object. 根据您的问题,您似乎想知道JSON对象中的属性计数。 So we can do that by following these steps: 因此,我们可以按照以下步骤操作:

STEP 1 : Parse the response string into JSON object 步骤1:将响应字符串解析为JSON对象

STEP 2 : Convert JSON object into groovy Map object 步骤2:将JSON对象转换为Groovy Map对象

Step 3 : Call size() method on Map object to get the elements count within the map object 步骤3:在Map对象上调用size()方法以获取map对象内的元素计数

So your code would like this : 所以你的代码会这样:

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()


def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')

def object = (Map)response.resource
log.info object.size()

So your output will be 2. You can try adding more elements to JSON object check if it works. 因此您的输出将为2。您可以尝试向JSON对象添加更多元素,以检查其是否有效。

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM