23

我正在尝试从 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));
    }
} 

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

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

将json写入文件:

File g = new File(tempDir+File.separator+'jsonObject.txt')
            g.createNewFile()
            def json = new JsonBuilder()
            json {
                "result" result
                }       
            g.setText(json.toString())
4

4 回答 4

60

请试试这个:

import groovy.json.JsonSlurper

def inputFile = new File("D:\\yourPath\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{ println it }
于 2013-10-23T05:38:23.027 回答
6

尝试:

File f = new File( tempDir, 'jsonObject.txt' )
if( f.exists() ) {
    def game = f.withReader { r ->
        new JsonSlurper().parse( r )
    }
    println game
}
于 2013-10-22T16:07:30.123 回答
1

尝试简单和优化的解决方案:

import groovy.json.JsonSlurper

try {
File inputFile = new File("your_file_path")
def slurper = new JsonSlurper()
def data = slurper.parse(inputFile)
} catch (Exception e) {
      e.printStackTrace()
    }
于 2019-05-07T06:40:15.170 回答
0

parseFile 可以将文件作为输入:

import groovy.json.JsonSlurper

def inputFile = new File("/your/path/my.json")
def InputJSON = new JsonSlurper().parseFile(inputFile, 'UTF-8')
InputJSON.each{ println it }
于 2017-11-29T09:05:04.487 回答