Groovy: isn't there a stringToMap out of the box?

前端 未结 5 1223
独厮守ぢ
独厮守ぢ 2020-12-30 23:30

as a tcl developer starting with groovy, I am a little bit surprised about the list and map support in groovy. Maybe I am missing something here.

I am used to conver

相关标签:
5条回答
  • 2020-12-31 00:01

    I think you are looking for a combination of ConfigObject and ConfigSlurper. Something like this would do the trick.

    def foo = new ConfigObject()
    foo.bar = [ 'a' : 2, 'b' : 4 ]
    
    // we need to serialize it
    new File( 'serialized.groovy' ).withWriter{ writer ->
      foo.writeTo( writer )
    }
    
    def config = new ConfigSlurper().parse(new File('serialized.groovy').toURL())    
    
    // highest level structure is a map ["bar":...], that's why we need one loop more
    config.each { _,v ->
        v.each {key, value -> println key + " " + value}
    }
    
    0 讨论(0)
  • 2020-12-31 00:13

    If you don't want to use evaluate(), do instead:

    def stringMap = "['a':2,'b':4]"
    stringMap = stringMap.replaceAll('\\[|\\]','')
    def newMap = [:]
    stringMap.tokenize(',').each {
    kvTuple = it.tokenize(':')
    newMap[kvTuple[0]] = kvTuple[1]
    }
    println newMap
    
    0 讨论(0)
  • 2020-12-31 00:15

    I hope this help:

        foo= "['a':2,'b':4]"
        Map mapResult=[:]
        mapResult += foo.replaceAll('\\[|\\]', '').split(',').collectEntries { entry ->
            def pair = entry.split(':')
            [(pair.first().trim()): pair.last().trim()]
           }
    
    0 讨论(0)
  • 2020-12-31 00:20

    You might want to try a few of your scenarios using evaluate, it might do what you are looking for.

    def stringMap = "['a':2,'b':4]"
    def map = evaluate(stringMap)
    
    assert map.a == 2
    assert map.b == 4
    
    def stringMapNested = "['foo':'bar', baz:['alpha':'beta']]"
    def map2 = evaluate(stringMapNested)
    
    assert map2.foo == "bar"
    assert map2.baz.alpha == "beta"
    
    0 讨论(0)
  • 2020-12-31 00:22

    Not exactly native groovy, but useful for serializing to JSON:

    import groovy.json.JsonBuilder
    import groovy.json.JsonSlurper
    
    def map = ['a':2,'b':4 ]
    def s = new JsonBuilder(map).toString()
    println s
    
    assert map == new JsonSlurper().parseText(s)
    

    with meta-programming:

    import groovy.json.JsonBuilder
    import groovy.json.JsonSlurper
    
    Map.metaClass.toJson   = { new JsonBuilder(delegate).toString() }
    String.metaClass.toMap = { new JsonSlurper().parseText(delegate) }
    
    def map = ['a':2,'b':4 ]
    assert map.toJson() == '{"a":2,"b":4}'
    assert map.toJson().toMap() == map
    

    unfortunately, it's not possible to override the toString() method...

    0 讨论(0)
提交回复
热议问题