Groovy:没有现成的 stringToMap 吗? [英] Groovy: isn't there a stringToMap out of the box?
问题描述
作为从 groovy 开始的 tcl 开发人员,我对 groovy 中的列表和地图支持感到有点惊讶.也许我在这里遗漏了一些东西.
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.
我习惯于在 tcl 中动态地在字符串、列表和数组/映射之间进行转换.在 tcl 中,类似
I am used to convert between strings, lists and arrays/maps in tcl on the fly. In tcl, something like
"['a':2,'b':4]".each {key, value -> println key + " " + value}
有可能,在 groovy 中, each 命令会遍历字符串的每个字符.
would be possible, where as in groovy, the each command steps through each character of the string.
这将是一个很大的问题,因为我可以轻松地使用诸如 split 或 tokenize 命令之类的东西,但是因为序列化列表或映射不仅仅是 "a:2,b:4",所以它有点难解析.
This would be much of a problem is I could easily use something like the split or tokenize command, but because a serialized list or map isn't just "a:2,b:4", it is a little bit harder to parse.
似乎 griffon 开发人员使用 stringToMap 库(http://code.google.com/p/stringtomap/) 但该示例也无法处理序列化映射.
It seems that griffon developers use a stringToMap library (http://code.google.com/p/stringtomap/) but the example can't cope with the serialized maps either.
所以我现在的问题是:在 groovy 中解析地图或列表的最佳方法是什么?
So my question is now: what's the best way to parse a map or a list in groovy?
干杯,拉尔夫
PS:这是一个很奇怪的问题,但我用 grails 标记了它,因为我需要这个功能用于 grails,我想通过 URL 传递地图
PS: it's a groovy question, but I've tagged it with grails, because I need this functionality for grails where I would like to pass maps through the URL
更新:这对我来说仍然是一个悬而未决的问题......所以这里有一些更新给那些有同样问题的人:
Update: This is still an open question for me... so here are some updates for those who have the same problem:
- 当您将 Map 转换为 String 时,
.toString()
将导致在所有情况下都无法将其转换回 Map 的结果,但是.inspect()
会给你一个字符串,它可以被评估回地图! - 在 Grails 中,有一个
.encodeAsJSON()
和JSON.parse(String)
- 两者都很好用,但我还没有检查解析器是什么将使用 JSON 函数(可能存在安全问题)
- when you turn a Map into a String, a
.toString()
will result in something which can't be turned back into a map in all cases, but an.inspect()
will give you a String which can be evaluated back to a map! - in Grails, there is a
.encodeAsJSON()
andJSON.parse(String)
- both work great, but I haven't checked out yet what the parser will do with JSON functions (possible security problem)
推荐答案
不完全是原生的 groovy,但对于序列化为 JSON 很有用:
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)
元编程:
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
不幸的是,无法覆盖 toString() 方法...
unfortunately, it's not possible to override the toString() method...
这篇关于Groovy:没有现成的 stringToMap 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!