我有一个UTF-8编码的文件。
我编写了一个groovy脚本来加载带有JSON结构的文件,修改它并保存它:
def originPreviewFilePath = "./xxx.json"
//target the file
def originFile = new File(originPreviewFilePath)
//load the UTF8 data file as a JSON structure
def originPreview = new JsonSlurper().parse(originFile,'UTF-8')
//Here is my own code to modify originPreview
//Convert the structure to JSON Text
def resultPreviewJson = JsonOutput.toJson(originPreview)
//Beautify JSON Text (Indent)
def finalFileData = JsonOutput.prettyPrint(resultPreviewJson)
//save the JSONText
new File(resultPreviewFilePath).write(finalFileData, 'UTF-8')
问题是JsonOutput.toJson
将UTF-8数据转换为UNICODE。我不明白为什么JsonSlurper().parse
可以使用UTF-8,而不能使用JsonOutput.toJson
。
如何让JsonOutput.toJson
使用UTF-8?我需要JsonSlurper().parse
的精确逆
发布于 2016-07-25 14:48:50
我认为编码是在读取本身时对不正确的语句应用的。
在语句下面更改:
def originFile = new File(originPreviewFilePath)
def originPreview = new JsonSlurper().parse(originFile,'UTF-8')
To:
def originFile = new File(originPreviewFilePath).getText('UTF-8')
def originPreview = new JsonSlurper().parseText(originFile)
发布于 2019-11-29 11:02:01
如果有人还在努力解决这个问题,解决方案是禁用unicode转义:
new JsonGenerator.Options()
.disableUnicodeEscaping()
.build()
.toJson(object)
发布于 2021-10-12 22:08:33
在Groovy 3中,这对我起了作用:
StringEscapeUtils.unescapeJavaScript(
JsonOutput.prettyPrint(resultPreviewJson)
)
https://stackoverflow.com/questions/38569874
复制相似问题