Suppose we have the following JSON data:
{
"TESTS":
[
{
"YEAR": "2017",
"MONTH": "June",
"DATE": "28"
}
]
}
import 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");
}
Below is the parser:
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
}
}