首页 > 解决方案 > 使用 Groovy 计算 JSON 对象中的项目

问题描述

我的 JSON 文件

{
    "General": [
        {
            "AppUrl": "abc.com/",
            "HTTPResponseCode": "200",
            "QA Build Version#": "4.3.44"
        }
    ]
}

我想获取上述 JSON 对象的计数元素(键值对)。

我尝试使用下面的代码,但它返回 acount为 1。

我的代码

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.size()

标签: javajsongroovy

解决方案


代替:

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.size()

应该:

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.keySet().size()

推荐阅读