Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Groovy JsonOutput.toJson with data encoded with UTF-8?

I have a file with UTF-8 encoding.

I write a groovy script to load a file with a JSON structure, modify it and save it:

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') 

The problem is that JsonOutput.toJson transforms UTF-8 data to UNICODE. I don't understand why JsonSlurper().parse can use UTF-8 but not JsonOutput.toJson?

How to have JsonOutput.toJson use UTF-8? I need to have the exact inverse of JsonSlurper().parse

like image 697
Damien Leroux Avatar asked Jul 25 '16 14:07

Damien Leroux


2 Answers

In case anyone is still struggling with this, the solution is to disable unicode escaping:

new JsonGenerator.Options()
    .disableUnicodeEscaping()
    .build()
    .toJson(object)
like image 82
adarshr Avatar answered Nov 04 '22 17:11

adarshr


This worked for me in Groovy 3:

StringEscapeUtils.unescapeJavaScript(
  JsonOutput.prettyPrint(resultPreviewJson)
)
like image 39
Pablo Pazos Avatar answered Nov 04 '22 17:11

Pablo Pazos