繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM