使用 Groovy 解析 JSON 文件

假设我们有以下 JSON 数据:

{
    "TESTS": 
    [
         {
              "YEAR": "2017",
              "MONTH": "June",
              "DATE": "28"                  
         }
    ]
}

导入 groovy.json.JsonSlurper

class JSONUtils {

private def data;
private def fileName = System.getProperty("jsonFileName")

public static void main(String[] args)
{
    JSONUtils jutils = new JSONUtils()
    def month = jutils.get("MONTH");
}    

下面是解析器:

private parseJSON(String fileName = "data.json")
{ 
    def jsonSlurper = new JsonSlurper()
    def reader

    if(this.fileName?.trim())
    {
        fileName = this.fileName
    }

    reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
    data = jsonSlurper.parse(reader);
    return data
}

def get(String item)
{
    def result = new ArrayList<String>();
    data = parseJSON()        
    data.TESTS.each{result.add(it."${item}")}
    return  result
}        

}