Sanket Deshpande Sanket Deshpande - 3 years ago 296
Groovy Question

Reading JSON object from txt file in Groovy

I am trying to collect a JSON from a txt file. But my below code seems to keep giving me "nullPointerException".

File f = new File(tempDir+File.separator+'jsonObject.txt')
if (f){
log.error " file exists $f"
FileReader f2 = new FileReader(f);
log.error " file data- $f2"
if (f2 == null) {
//do something
} else {
JsonSlurper jsonParser = new JsonSlurper();
game = jsonParser.parse(new FileReader(f));


Reading a json txt file:

File f = new File(tempDir+File.separator+'jsonObject.txt')
def slurper = new JsonSlurper()
def jsonText = f.getText()
json = slurper.parseText( jsonText )

Writing json to a file:

File g = new File(tempDir+File.separator+'jsonObject.txt')
def json = new JsonBuilder()
json {
"result" result

Answer Source

Please, try this:

import groovy.json.JsonSlurper

def inputFile = new File("D:\\yourPath\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{ println it }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download