欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

相关标签: Groovy JsonOutput