groovy:将字符串(这是一个列表)转换为 Groovy 列表

groovy: convert string (which is a list) to a Groovy List

import groovy.json.JsonSlurper

def ver = "['a', 'b', 'c']"
def jsonSlurper = new JsonSlurper()
def ver_list = jsonSlurper.parseText(ver)
println ver_list

这就是我正在做的。我想遍历 ver_list。而且似乎很难找到解决方案。

这是我打印ver_list时的错误:

Caught: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']
.^
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']

有效的 json 字符串必须用双引号引起来。

所以在你的代码中更改这一行,它应该可以工作:

def ver = '["a", "b", "c"]'

然而,如果您需要解析无效的 json,您可以尝试使用 LAX 解析器。

那么下面的字符串也能被解析

import groovy.json.JsonSlurper
import groovy.json.JsonParserType

def ver = "[a, 'b', 001]"
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def ver_list = jsonSlurper.parseText(ver)
println ver_list