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

后端 未结 8 1873
情深已故
情深已故 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条回答
  •  隐瞒了意图╮
    2020-12-31 08:07

    After some searching, "collectEntries()" is the magic thing to use, it creates a map element. Work just like "collect()" that creates a list. So given

    def params = "a1=b1&a2=b2&a3&a4=&a5=x=y"
    

    the one-liner is

    map = params.tokenize("&").collectEntries{ 
              it.split("=",2).with{ 
                  [ (it[0]): (it.size()<2) ? null : it[1] ?: null ] 
              }
          }
    

    which creates

    map = [a1:b1, a2:b2, a3:null, a4:null, a5:x=y]
    

    Depending how you want to handle the cases "a3" and "a4=" you can also use a slightly shorter version

    ...
    [ (it[0]): (it.size()<2) ? null : it[1] ] 
    ...
    

    and then you get this:

    map = [a1:b1, a2:b2, a3:null, a4:, a5:x=y]
    

提交回复
热议问题