You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中JsonSlurper和JsonOutput特殊符号转义异常如何解决

问题根源

这不是解析错误,是Groovy内置JsonOutput的默认序列化规则导致的:它会自动把所有ASCII范围外的字符转成\uXXXX格式的Unicode转义序列。按照JSON官方规范,¢和\u00a2语义完全等价,属于合法JSON写法,但如果对接的下游系统不识别这类转义,就需要调整输出规则保留原始字符。
注意这个问题和JsonSlurper解析无关,转义只发生在最后调用JsonOutput.toJson()的序列化阶段。

修复方案

方案1:使用JsonGenerator自定义序列化规则(推荐,Groovy 2.5及以上版本支持)

不要直接调用JsonOutput.toJson(),改用官方提供的可配置JsonGenerator实例,显式关闭非ASCII字符转义逻辑,不会破坏原有JSON结构,也不会出现误转换问题:

import groovy.json.JsonGenerator
import groovy.json.JsonSlurper

def body = message.getBody(java.lang.String)
def JSONInput = new JsonSlurper().parseText(body)

JSONInput.data.ProductStorePrices.each{
    if(it.Price != null){
        it.Price = it.Price.toDouble()
    }
    if(it.Active != null){
        it.Active = it.Active.toBoolean()
    }
}
// 构建关闭Unicode转义的序列化器
def generator = new JsonGenerator.Options()
    .disableUnicodeEscaping()
    .build()
message.setBody(generator.toJson(JSONInput))

方案2:手动反转义Unicode序列(兼容Groovy 2.5以下版本)

如果使用的Groovy版本较低没有JsonGenerator,可以在序列化完成后通过正则匹配,把所有\uXXXX格式的转义序列还原为原始字符:

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import java.util.regex.Matcher
import java.util.regex.Pattern

def body = message.getBody(java.lang.String)
def JSONInput = new JsonSlurper().parseText(body)

JSONInput.data.ProductStorePrices.each{
    if(it.Price != null){
        it.Price = it.Price.toDouble()
    }
    if(it.Active != null){
        it.Active = it.Active.toBoolean()
    }
}
def jsonStr = JsonOutput.toJson(JSONInput)
// 匹配并还原Unicode转义字符
Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})")
Matcher matcher = pattern.matcher(jsonStr)
StringBuffer sb = new StringBuffer()
while (matcher.find()) {
    matcher.appendReplacement(sb, String.valueOf((char) Integer.parseInt(matcher.group(1), 16)))
}
matcher.appendTail(sb)
message.setBody(sb.toString())

注意:该方案会全局替换所有匹配到的Unicode转义序列,如果原始业务字段中本身存在字面量形式的\uXXXX文本(非转义生成、是用户输入的原始内容),会被误转换,这类场景优先使用方案1。

调整后的脚本输出的JSON会保留UnitPrice字段里的¢原字符,同时Price转数值、Active转布尔值的逻辑完全正常。

内容的提问来源于stack exchange,提问作者sravan kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 05:48:34