在 Groovy 中从 txt 文件中读取 JSON 对象 [英] Reading JSON object from txt file in Groovy
本文介绍了在 Groovy 中从 txt 文件中读取 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 txt 文件中收集 JSON.但是我下面的代码似乎一直给我nullPointerException".
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));
}
}
找到解决方案
读取一个json txt文件:
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 )
将json写入文件:
File g = new File(tempDir+File.separator+'jsonObject.txt')
g.createNewFile()
def json = new JsonBuilder()
json {
"result" result
}
g.setText(json.toString())
推荐答案
请试试这个:
import groovy.json.JsonSlurper
def inputFile = new File("D:\yourPath\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{ println it }
这篇关于在 Groovy 中从 txt 文件中读取 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文