首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将Groovy JsonOutput.toJson与UTF-8编码的数据一起使用?

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

Stack Overflow用户
提问于 2016-07-25 14:03:42
回答 3查看 8.7K关注 0票数 7

我有一个UTF-8编码的文件。

我编写了一个groovy脚本来加载带有JSON结构的文件,修改它并保存它:

代码语言:javascript
运行
复制
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的精确逆

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-07-25 14:48:50

我认为编码是在读取本身时对不正确的语句应用的。

在语句下面更改:

代码语言:javascript
运行
复制
def originFile = new File(originPreviewFilePath)
def originPreview = new JsonSlurper().parse(originFile,'UTF-8')

To:

代码语言:javascript
运行
复制
def originFile = new File(originPreviewFilePath).getText('UTF-8')
def originPreview = new JsonSlurper().parseText(originFile)
票数 0
EN

Stack Overflow用户

发布于 2019-11-29 11:02:01

如果有人还在努力解决这个问题,解决方案是禁用unicode转义:

代码语言:javascript
运行
复制
new JsonGenerator.Options()
    .disableUnicodeEscaping()
    .build()
    .toJson(object)
票数 11
EN

Stack Overflow用户

发布于 2021-10-12 22:08:33

在Groovy 3中,这对我起了作用:

代码语言:javascript
运行
复制
StringEscapeUtils.unescapeJavaScript(
  JsonOutput.prettyPrint(resultPreviewJson)
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38569874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档