使用Groovy将JSON漂亮地打印到文件中,而不使用unicode转义

zsbz8rwp  于 6个月前  发布在  其他
关注(0)|答案(2)|浏览(80)

我一直在谷歌和所以试图找出我如何可以漂亮打印JSON到一个文件使用groovy没有Unicode字符得到转义。

String json = JsonOutput.toJson([name: 'Johan Söder', age: 42])
String prettyJson = JsonOutput.prettyPrint(json)
File newFile = new File("data.json")
newFile.write(prettyJson)

字符串
这将导致文件内容如下所示:

{
    "name": "Johan S\u00f6der",
    "age": 42
}


使用JsonGenerator和选项disableUnicodeEscaping工作,但JsonGenerator没有漂亮的打印选项,所以它看起来像这样:

{"name":"Johan Söder","age":42}


这对于这个小例子来说是很好的,但是我的真实的输出并没有这么小,需要打印得很漂亮。
将JsonGenerator的结果传递给JsonOutput.prettyPrint重新引入了unicode转义字符。将prettyPrint从JsonOutput传递给JsonGenerator会造成一团混乱:

"{\n    \"name\": \"Johan S\\u00f6der\",\n    \"age\": 42\n}"


与unicode escped字符,甚至没有漂亮的打印。
我也尝试过使用JsonBuilder和JsonGenerator:

JsonGenerator generator = new JsonGenerator.Options().disableUnicodeEscaping().build()
String prettyString = new JsonBuilder([name: 'Johan Söder', age: 42], generator).toPrettyString()
File newFile = new File("data.json")
newFile.write(prettyString)


但结果还是一样:

{
    "name": "Johan S\u00f6der",
    "age": 42
}


所以现在我发布这个问题,希望有人有解决方案,能够漂亮地打印到一个没有Unicode转义字符的文件。我想要一个没有额外库的Groovy解决方案。

pdtvr36n

pdtvr36n1#

使用StringEscapeUtils.unescapeJavaScript似乎可以做到这一点:

import groovy.json.*

String json = JsonOutput.toJson([name: 'Johan Söder', age: 42])
String prettyJson = StringEscapeUtils.unescapeJavaScript(
    JsonOutput.prettyPrint(json)
)
File newFile = new File("data.json")
newFile.write(prettyJson)

字符串
编辑:正如@daggett正确地指出的那样,这将取消转义特殊字符,如",使json文件无效,如果存在的话。我首先感到惊讶的是,没有内置的方法来处理这一点。即使apache commons unescapeJson似乎也和unescapeJavaScript一样。
使用Google gson

@Grab('com.google.code.gson:gson:2.10.1')
import com.google.gson.*

String prettyString = new GsonBuilder()
    .setPrettyPrinting()
    .create()
    .toJson([name: 'Johan " Söder', age: 42])

File newFile = new File("data.json")
newFile.write(prettyString)

1hdlvixo

1hdlvixo2#

我建议只取消转义unicode字符

import groovy.json.*

String json = JsonOutput.toJson([name: 'Johan " Söder', age: 42]) // added doublequote for test
String prettyJson = JsonOutput.prettyPrint(json)
prettyJson = prettyJson.replaceAll(/\\u([0-9a-fA-F]{4})/){Integer.parseInt(it[1], 16) as char}
File newFile = new File("data.json")
newFile.write(prettyJson)

字符串
结果:

{
    "name": "Johan \" Söder",
    "age": 42
}

相关问题