将String变量转换为List [Groovy]

问题描述 投票:20回答:4

如何将此String变量转换为List

def ids = "[10, 1, 9]"

我尝试过:作为ListtoList();

java string list groovy
4个回答
24
投票
def l = Eval.me(ids)

采用groovy代码的字符串(在本例中为“[10,1,9]”)并将其评估为groovy。这将为您提供3个整数的列表。


19
投票
def l = ids.split(',').collect{it as int}

13
投票

使用内置的JsonSlurper

一旦数据类型发生变化,Using Eval is not the best solution in most cases和字符串操作解决方案将失败,因此它不具有适应性。所以最好使用JsonSlurper

import groovy.json.JsonSlurper

def ids = "[10, 1, 9]"
def idList = new JsonSlurper().parseText(ids)

assert 10 == idList[0]

0
投票

这对我有用。并且Eval.me将无法在Jenkins groovy脚本中工作。我试过了。

assert "[a,b,c]".tokenize(',[]') == [a,b,c]
© www.soinside.com 2019 - 2024. All rights reserved.