【问题标题】:How to use Groovy JsonOutput.toJson with data encoded with UTF-8?如何将 Groovy JsonOutput.toJson 与 UTF-8 编码的数据一起使用?
【发布时间】:2016-11-28 22:06:05
【问题描述】:

我有一个 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 完全相反

【问题讨论】:

    标签: json unicode encoding groovy utf-8


    【解决方案1】:

    这在 Groovy 3 中对我有用:

    StringEscapeUtils.unescapeJavaScript(
      JsonOutput.prettyPrint(resultPreviewJson)
    )
    

    【讨论】:

      【解决方案2】:

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

      new JsonGenerator.Options()
          .disableUnicodeEscaping()
          .build()
          .toJson(object)
      

      【讨论】:

      • JsonGenerator 是一个接口,它是如何工作的?显示一个完整的例子。
      • @PabloPazos 这是完整的示例。 JsonGenerator 是一个接口,但我们正在实例化名为 Options 的静态嵌套类。有关说明和另一个示例,请参见 docs.groovy-lang.org/latest/html/api/groovy/json/…
      • 要完整,它需要定义“对象”。注意:JsonGenerator 在 Groovy 2.4.x 中不可用
      • @adarshr 感谢您的回复,但不幸的是,JsonOutput.prettyPrint 应用 unicode 的方式与 JsonOutput.toJson 相同。而且 JsonGenerator 没有 prettyPrint 方法/选项。
      • 它在 Groovy 3 中不起作用。起作用的是 JsonOutput.prettyPrint 和 StringEscapeUtils.unescapeJavaScript
      【解决方案3】:

      我认为在读取自身时,编码应用在了错误的语句中。

      从以下语句更改:

      def originFile = new File(originPreviewFilePath)
      def originPreview = new JsonSlurper().parse(originFile,'UTF-8')
      

      收件人:

      def originFile = new File(originPreviewFilePath).getText('UTF-8')
      def originPreview = new JsonSlurper().parseText(originFile)
      

      【讨论】:

      • 这没有效果。问题是 JsonOutput.toJson 使用 unicode 与输入无关。
      • 我和 Johannes 有同样的问题 - groovy.json.JsonOutput.toJson(["тест":"кирилиця"]) 在 toString() 调用上产生转义序列,groovy.json.JsonOutput 也是如此.prettyPrint(groovy.json.JsonOutput.toJson(["тест":"кирилиця"]))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2018-01-27
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      相关资源
      最近更新 更多