2014-09-10 147 views
5

我有一個類似於下面的JSON文檔,我試圖在Groovy中解析它。基本上每個學校(學校信息),我想抓住SCHOOL_COUNTRY和其他領域。我正在嘗試下面的代碼,但它沒有返回我所需要的。對於列出的每個學校(1000的),我想抓住只有特定的部分,例如:Groovy - JsonSlurper解析JSON文件

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

回答

8

我不知道這是否是唯一的錯誤,但你無法讀取eachschoolInfo.SCHOOL_NAMESCHOOL_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 
2

在這裏你去:

import groovy.json.JsonSlurper 

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

def slurper = new JsonSlurper().parseText(t) 
slurper.each { 
    println it.SCHOOL_INFO."SCHOOL NAME" 
} 

我不知道是否應該有_登錄學校名稱

1
println it.SCHOOL_INFO."SCHOOL NAME" 

這應該沒有_符號工作。