从Groovy中的txt文件中读取JSON对象

San*_*nde 18 grails groovy

我正在尝试从txt文件中收集JSON.但我的下面的代码似乎继续给我"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));
    }
} 
Run Code Online (Sandbox Code Playgroud)

找到解决方案
读取json txt文件:

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

将json写入文件:

File g = new File(tempDir+File.separator+'jsonObject.txt')
            g.createNewFile()
            def json = new JsonBuilder()
            json {
                "result" result
                }       
            g.setText(json.toString())
Run Code Online (Sandbox Code Playgroud)

oly*_*lyv 50

请试试这个:

import groovy.json.JsonSlurper

def inputFile = new File("D:\\yourPath\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{ println it }
Run Code Online (Sandbox Code Playgroud)


tim*_*tes 5

尝试:

File f = new File( tempDir, 'jsonObject.txt' )
if( f.exists() ) {
    def game = f.withReader { r ->
        new JsonSlurper().parse( r )
    }
    println game
}
Run Code Online (Sandbox Code Playgroud)