Created
March 10, 2026 23:35
-
-
Save ppazos/5455a61fbd7cb9afdca31e6da17320ee to your computer and use it in GitHub Desktop.
Right way of having Groovy 3 encode spanish characters in UTF8 without adding the octal notation, with and without pretty print.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import groovy.json.JsonGenerator | |
| import groovy.json.StreamingJsonBuilder | |
| def data = [name: "Café", message: "Hello"] | |
| def generator = new JsonGenerator.Options() | |
| .disableUnicodeEscaping() | |
| .build() | |
| def stringWriter = new StringWriter() | |
| // The builder will use your generator settings | |
| def builder = new StreamingJsonBuilder(stringWriter, generator) | |
| builder.call(data) | |
| // No pretty print | |
| println stringWriter.toString() | |
| // Pretty print and avoids /unnnn characters | |
| import groovy.json.JsonOutput | |
| // 1. Generate and pretty-print (this will create \u00e9 and \u4e16\u754c) | |
| String escapedPrettyJson = JsonOutput.prettyPrint(JsonOutput.toJson(data)) | |
| // 2. Use Regex to convert \uXXXX sequences back to literal UTF-8 characters | |
| String unescapedJson = escapedPrettyJson.replaceAll(/\\u([0-9a-fA-F]{4})/) { match -> | |
| Integer.parseInt(match[1], 16) as char | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment