我有一个类似于以下结构的JSON文档,并且我试图在Groovy中对其进行解析。基本上,对于每个学校(学校信息),我都希望获取SCHOOL_COUNTRY和其他字段。我正在下面尝试此代码,但未返回我需要的代码。对于列出的每所学校(1,000所),我只想获取特定部分,例如:

def parseJSON(long id) {

    JSONFile fileInstance = JSONFile.get(id)
    def json = new JsonSlurper().setType(RELAX).parse(new FileReader(fileInstance.filePath))
    def schoolInfo = json.SCHOOL_INFO
    def schoolName = json.SCHOOL_INFO.SCHOOL_NAME
    schoolInfo.each {
       render(schoolInfo.SCHOOL_NAME)
    }
}

因此,基本上对于每所学校,只需打印出学校名称即可。 JSON结构:
[{
    "SCHOOL_INFO": {
        "SCHOOL_COUNTRY": "Finland",
        "SCHOOL NAME": "Findland Higher Learning"
     },
     "LOCATION": {
         "LONGITUDE": "24.999",
         "LATITUDE": "61.001"
     }
}]

最佳答案

我不确定这是否是唯一的错误,但是您无法在schoolInfo.SCHOOL_NAME中读取eachSCHOOL_NAMEjson.SCHOOL_INFO的属性,因此it.SCHOOL_NAME是访问它的正确方法。请看下面的示例:

import groovy.json.JsonSlurper

def jsonAsText = '''[{
    "SCHOOL_INFO": {
        "SCHOOL_COUNTRY": "Finland",
        "SCHOOL NAME": "Findland Higher Learning"
    },
    "LOCATION": {
        "LONGITUDE": "24.999",
        "LATITUDE": "61.001"
    }
}]'''

def json = new JsonSlurper().parseText(jsonAsText)

def schoolInfo= json.SCHOOL_INFO
schoolInfo.each{
    println it."SCHOOL NAME"
}

它打印:
Findland Higher Learning

10-07 21:51