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)); } }
SOLUTION FOUND
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') g.createNewFile() def json = new JsonBuilder() json { "result" result } g.setText(json.toString())
JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.
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 }
try:
File f = new File( tempDir, 'jsonObject.txt' ) if( f.exists() ) { def game = f.withReader { r -> new JsonSlurper().parse( r ) } println game }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With