为什么Groovy不能正确地将字符串数组转换为JSON?

z0qdvdin  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(241)

我有一个String,其中包含一个String数组,我将其转换为groovy数组(使用split函数),然后我使用JsonOutput.toJson将该数组转换为JSON,如下所示。

def orignal = "[  \"Backsplash\",  \"Kitchen Wall\",  \"Wall Tile\",  \"Bathroom Wall\"]"
def originalAsArray = orignal.toString().split(",")
JsonOutput.toJson(originalAsArray)

此操作的输出为

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

这是一个包含一个String元素的数组,而我期望的是一个包含多个String元素的数组,如下所示

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

为什么数组未按预期进行转换?

91zkwejq

91zkwejq1#

// Given the original String
def original = '[  "Backsplash",  "Kitchen Wall",  "Wall Tile",  "Bathroom Wall"]'

// The easiest way of parsing it (as it's valid JSON already)
def list = new groovy.json.JsonSlurper().parseText(original)

// And we get a list of Strings:
assert list.size() == 4
assert list[0] == 'Backsplash'
assert list[3] == 'Bathroom Wall'

// To put this back into a JSON string, we just need to do:
def output = groovy.json.JsonOutput.toJson(list)

// Which gives us the string as expected:
assert output == '["Backsplash","Kitchen Wall","Wall Tile","Bathroom Wall"]'

相关问题