Peter Sun
Peter Sun

Reputation: 1813

Inject String to Map - Groovy

I am new to Groovy and working on a device handler for my Smartthing Hub which is written in Groovy. I am having trouble parsing a string.

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!"
        }
    }
 }

Output:

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]

Two questions:
1. Why is the variable, map, null?
2. Why is the function not printing the nameAndValue->'tempImageKey' info?

Upvotes: 1

Views: 305

Answers (1)

tim_yates
tim_yates

Reputation: 171084

  1. map cannot be null, if(map) checks if it's null or empty...and it will not be null in this situation (so long as you follow #2)
  2. You need to return map from the inject closure, so that is can be aggregated.

    test.inject([:]) { map, param ->
        def nameAndValue = param.split(":")
        println "nameAndValue: ${nameAndValue}"
        map.put(nameAndValue[0].trim(),nameAndValue[1].trim())
        map
    }
    

A simpler version of what you're trying would be:

description.split(',')*.trim()*.tokenize(':').collectEntries()

Upvotes: 2

Related Questions