Groovy JsonOutput 中文转码
程序员文章站
2024-03-23 18:12:34
...
JsonOutput.toJson()的时候,会把中文转成Unicode字符
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def json_text ="""
{"name":"兰兮"}
""";
def slurper = new JsonSlurper()
def json_object = slurper.parseText(json_text)
log.info json_object
def output = new JsonOutput()
def json_text_toJson = output.toJson(json_object)
log.info json_text_toJson
输出为:
Tue Oct 09 15:50:39 CST 2018: INFO: {name=兰兮}
Tue Oct 09 15:50:39 CST 2018: INFO: {"name":"\u5170\u516e"}
解决转码其实很简单,因为Groovy兼容java,使用java第三方包去toJson操作。
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import com.fasterxml.jackson.databind.ObjectMapper
def json_text ="""
{"name":"兰兮"}
""";
def slurper = new JsonSlurper()
def json_object = slurper.parseText(json_text)
log.info json_object
def output = new JsonOutput()
def json_text_toJson = output.toJson(json_object)
log.info json_text_toJson
ObjectMapper mapper = new ObjectMapper();
String json_text_jackson = mapper.writeValueAsString(json_object);
log.info json_text_jackson
输出:
Tue Oct 09 15:58:12 CST 2018: INFO: {name=兰兮}
Tue Oct 09 15:58:12 CST 2018: INFO: {"name":"\u5170\u516e"}
Tue Oct 09 15:58:12 CST 2018: INFO: {"name":"兰兮"}
!!!!DONE
上一篇: 【温故而知新】Spring容器
下一篇: RS信道编码(matlab)