将代表字符串的键值转换为列表

时间:2019-06-04 10:13:57

标签: groovy

我有一个字符串,类似

'Content-Type: application/json' \
'Postman-Token: a47537e5-b4b0-4915-93c8-92acf4b21e70' \
'cache-control: no-cache' \

我想要类似

的格式
['Content-Type' : 'application/json','Postman-Token' : 'a47537e5-b4b0-4915-93c8-92acf4b21e70','cache-control' : 'no-cache']

1 个答案:

答案 0 :(得分:0)

以下是为您提供的代码:

def tokens = 'Content-Type: application/json Postman-Token: a47537e5-b4b0-4915-93c8-92acf4b21e70 cache-control: no-cache'.minus(":").replaceAll(":", "") .split(" ")
def map2 = [ : ]
def i = 0
0.step(tokens.length, 2) {
    map2.put(tokens[i], tokens[i+1])
    i = i + 2
}

println JsonOutput.toJson(map2)

结果:

 {"Content-Type":"application/json","Postman-Token":"a47537e5-b4b0-4915-93c8-92acf4b21e70","cache-control":"no-cache"}