Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading JSON object from txt file in Groovy

Tags:

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()) 
like image 210
Sanket Deshpande Avatar asked Oct 22 '13 16:10

Sanket Deshpande


People also ask

What is JsonSlurper Groovy?

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.


2 Answers

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 } 
like image 50
olyv Avatar answered Sep 20 '22 06:09

olyv


try:

File f = new File( tempDir, 'jsonObject.txt' ) if( f.exists() ) {     def game = f.withReader { r ->         new JsonSlurper().parse( r )     }     println game } 
like image 29
tim_yates Avatar answered Sep 20 '22 06:09

tim_yates