Best way to code this, string to map conversion in Groovy

后端 未结 8 1990
情深已故
情深已故 2020-12-31 07:22

I have a string like

def data = \"session=234567893egshdjchasd&userId=12345673456&timeOut=1800000\"

I want to convert it to a map

8条回答
  •  -上瘾入骨i
    2020-12-31 07:51

    I wouldn't suggest using split at all.

    Split creates a new string, whereas when creating a collection of environment variables, you would probably want a list of maps.

    Tokenize both on the initial break (&) and on the nested break (=). While most interpreters will still work, some may run the split literally, and you'll end up with a list of strings, rather than a list of maps.

    def data= "test1=val1&test2=val2"
    def map = [:]
    
    map = data.tokenize("&").collectEntries {
        it.tokenize("=").with {
            [(it[0]):it[1]]
        }
    }
    

提交回复
热议问题