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

Groovy无法正确将字符串数组转为JSON的原因是什么?

JSON字符串数组转Groovy数组不符合预期的原因及解决方法

问题根源

你用split(",")处理JSON格式字符串的方式完全忽略了JSON的语法结构:

  • 原字符串是标准的JSON数组,开头的[和结尾的]是JSON数组的标记,直接split后第一个元素会带上[ ",最后一个元素会带上"]
  • split只会按逗号机械拆分,不会处理每个元素前后的引号和多余空格,导致最终每个元素都带着冗余符号,转成JSON后就成了包含垃圾内容的字符串数组。

正确解决方案:用JSON解析工具处理

既然原字符串是合法的JSON,直接用Groovy自带的JsonSlurper解析即可,它能准确识别JSON结构,直接转成Groovy的List:

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def original = "[  \"Backsplash\",  \"Kitchen Wall\",  \"Wall Tile\",  \"Bathroom Wall\"]"
def originalAsArray = new JsonSlurper().parseText(original)
def outputJson = JsonOutput.toJson(originalAsArray)

println outputJson

执行后输出符合预期:

["Backsplash","Kitchen Wall","Wall Tile","Bathroom Wall"]

不推荐的手动处理方式(仅作参考)

如果非要用split实现,需要额外清理每个元素的冗余内容,但这种方法有局限性(比如元素包含逗号时会出错):

import groovy.json.JsonOutput

def original = "[  \"Backsplash\",  \"Kitchen Wall\",  \"Wall Tile\",  \"Bathroom Wall\"]"
def originalAsArray = original
    .replaceAll(/^\[|\]$/, '') // 移除首尾的方括号
    .split(",")
    .collect { 
        it.replaceAll(/^"\s*|\s*"$/, '').trim() // 移除前后的引号和空格
    }

def outputJson = JsonOutput.toJson(originalAsArray)
println outputJson

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:05:28