将字符串注入地图 - Groovy
Inject String to Map - Groovy
我是 Groovy 的新手,正在为我的 Smartthing Hub 使用 Groovy 编写的设备处理程序。我在解析字符串时遇到问题。
def parseDescriptionAsMap(description) {
println "description: '${description}"
def test = description.split(",")
println "test: '${test}"
test.inject([:]) { map, param ->
def nameAndValue = param.split(":")
println "nameAndValue: ${nameAndValue}"
if(map)
{
println "map is NOT NULL"
map.put(nameAndValue[0].trim(),nameAndValue[1].trim())
}
else
{
println "map is NULL!"
}
}
}
输出:
description: 'index:17, mac:AAA, ip:BBB, port:0058, requestId:ce6598b2-fe8b-463d-bdf3-01ec35055f7a, tempImageKey:ba416127-14e3-4c7b-8f1f-5b4d633102e5
test: '[index:17, mac:AAA, ip:BBB, port:0058, requestId:ce6598b2-fe8b-463d-bdf3-01ec35055f7a, tempImageKey:ba416127-14e3-4c7b-8f1f-5b4d633102e5]
nameAndValue: [index, 17]
nameAndValue: [ mac, AAA]
map is NULL!
nameAndValue: [ ip, BBB]
map is NULL!
map is NULL!
nameAndValue: [ port, 0058]
nameAndValue: [ requestId, ce6598b2-fe8b-463d-bdf3-01ec35055f7a]
两个问题:
1. 为什么变量map为null?
2. 为什么函数不打印nameAndValue->'tempImageKey' info?
- map 不能为 null,
if(map)
检查它是否为 null 或空...在这种情况下它不会为 null(只要您遵循#2)
您需要从 inject
闭包中 return map
,以便可以聚合。
test.inject([:]) { map, param ->
def nameAndValue = param.split(":")
println "nameAndValue: ${nameAndValue}"
map.put(nameAndValue[0].trim(),nameAndValue[1].trim())
map
}
您正在尝试的更简单版本是:
description.split(',')*.trim()*.tokenize(':').collectEntries()
我是 Groovy 的新手,正在为我的 Smartthing Hub 使用 Groovy 编写的设备处理程序。我在解析字符串时遇到问题。
def parseDescriptionAsMap(description) {
println "description: '${description}"
def test = description.split(",")
println "test: '${test}"
test.inject([:]) { map, param ->
def nameAndValue = param.split(":")
println "nameAndValue: ${nameAndValue}"
if(map)
{
println "map is NOT NULL"
map.put(nameAndValue[0].trim(),nameAndValue[1].trim())
}
else
{
println "map is NULL!"
}
}
}
输出:
description: 'index:17, mac:AAA, ip:BBB, port:0058, requestId:ce6598b2-fe8b-463d-bdf3-01ec35055f7a, tempImageKey:ba416127-14e3-4c7b-8f1f-5b4d633102e5
test: '[index:17, mac:AAA, ip:BBB, port:0058, requestId:ce6598b2-fe8b-463d-bdf3-01ec35055f7a, tempImageKey:ba416127-14e3-4c7b-8f1f-5b4d633102e5]
nameAndValue: [index, 17]
nameAndValue: [ mac, AAA]
map is NULL!
nameAndValue: [ ip, BBB]
map is NULL!
map is NULL!
nameAndValue: [ port, 0058]
nameAndValue: [ requestId, ce6598b2-fe8b-463d-bdf3-01ec35055f7a]
两个问题:
1. 为什么变量map为null?
2. 为什么函数不打印nameAndValue->'tempImageKey' info?
- map 不能为 null,
if(map)
检查它是否为 null 或空...在这种情况下它不会为 null(只要您遵循#2) 您需要从
inject
闭包中 returnmap
,以便可以聚合。test.inject([:]) { map, param -> def nameAndValue = param.split(":") println "nameAndValue: ${nameAndValue}" map.put(nameAndValue[0].trim(),nameAndValue[1].trim()) map }
您正在尝试的更简单版本是:
description.split(',')*.trim()*.tokenize(':').collectEntries()