我正在尝试从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())
答案 0 :(得分:43)
请试试这个:
import groovy.json.JsonSlurper
def inputFile = new File("D:\\yourPath\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{ println it }
答案 1 :(得分:5)
尝试:
File f = new File( tempDir, 'jsonObject.txt' )
if( f.exists() ) {
def game = f.withReader { r ->
new JsonSlurper().parse( r )
}
println game
}
答案 2 :(得分: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 }
答案 3 :(得分:0)
尝试简单且优化的解决方案:
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()
}