如何将 Groovy JsonOutput.toJson 与用 UTF-8 编码的数据一起使用?

Dam*_*oux 5 unicode groovy encoding json utf-8

我有一个 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') 
Run Code Online (Sandbox Code Playgroud)

问题是JsonOutput.toJson将 UTF-8 数据转换为 UNICODE。我不明白为什么JsonSlurper().parse可以使用 UTF-8 而不是JsonOutput.toJson

如何JsonOutput.toJson使用UTF-8?我需要精确的倒数JsonSlurper().parse

ada*_*shr 8

如果有人仍在为此苦苦挣扎,解决方案是禁用 unicode 转义:

new JsonGenerator.Options()
    .disableUnicodeEscaping()
    .build()
    .toJson(object)
Run Code Online (Sandbox Code Playgroud)


Rao*_*Rao 1

我相信在阅读本身时,编码被应用于错误的语句。

更改以下语句:

def originFile = new File(originPreviewFilePath)
def originPreview = new JsonSlurper().parse(originFile,'UTF-8')
Run Code Online (Sandbox Code Playgroud)

到:

def originFile = new File(originPreviewFilePath).getText('UTF-8')
def originPreview = new JsonSlurper().parseText(originFile)
Run Code Online (Sandbox Code Playgroud)

  • 这没有效果。问题是“JsonOutput.toJson”无论输入如何都使用unicode。 (3认同)