2017-02-26 65 views
1

我是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.爲什麼是可變的,地圖,空?
2.爲什麼函數不打印nameAndValue - >'tempImageKey'info?

回答

2
  1. 地圖不能爲空,if(map)檢查它是否爲空或空...它不會在這種情況下,空(只要你遵循#2)
  2. 你需要從返回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()