# 2020/09/17 #「Groovy」- Handling the conversion between Object and JSON String

Object => JSON String

The following code can convert objects (List, Map) into Json String:

import groovy.json.JsonOutput

return JsonOutput.toJson(dataObject)

However, if the data contains Unicode characters, toJson() will escape them. The following examples and solutions:

import groovy.json.JsonOutput
import groovy.json.JsonGenerator.Options

def mapWithUnicode = [key : "好"]

println JsonOutput.toJson(mapWithUnicode)
// {"key":"\u597d"}

println new Options().disableUnicodeEscaping().build().toJson(mapWithUnicode)
// {"key":"好"}

However, JsonGenerator.Options cannot be used in Groovy 2.4.x, it will prompt an error of “unable to resolve class groovy.json.JsonGenerator.Options”. Because of the Groovy 2.4 version used in Jenkins Pipeline (09/16/2020 Jenkins 2.241), we must solve this problem.

In order to solve the above problems, we can turn to third-party libraries, such as the Gson library:

@Grab (group = 'com.google.code.gson', module = 'gson', version = '2.8.2')
import com.google.gson.Gson

println new Gson().toJson([key : "好"])
// {"key":"好"}

JSON String => Object

import groovy.json.JsonSlurperClassic

return new JsonSlurperClassic().parseText(jsonString)

references

K4NZ / 处理 Object 与 JSON String 之间的转换
Parsing and producing JSON
How to parse JSON in Java - Stack Overflow
json - How to use Groovy JsonOutput.toJson with data encoded with UTF-8? - Stack Overflow

Guess you like

Origin blog.csdn.net/u013670453/article/details/108679281