【问题标题】:How to convert a Groovy map to key="value" string?如何将 Groovy 映射转换为 key="value" 字符串?
【发布时间】:2016-04-17 11:31:22
【问题描述】:

我需要获取 map 并将其转换为字符串,其中键/值对分隔为 key="value"。 我可以执行以下操作,这很有效,但是有没有“groovier”的方式来实现这一点?

void "test map to string"() {
given: "a map"
Map fields = [class: 'blue', type:'sphere', size: 'large' ]

when:
StringBuilder stringBuilder = new StringBuilder()
fields.each() { attr ->
    stringBuilder.append(attr.key)
    stringBuilder.append("=")
    stringBuilder.append('"')
    stringBuilder.append(attr.value)
    stringBuilder.append('" ')
}

then: 'key/value pairs separated into key="value"'
'class="blue" type="sphere" size="large" ' == stringBuilder.toString()
}

【问题讨论】:

  • 如果这是 html(或 xml),请记住,您可能必须引用甚至编码这些值。

标签: groovy


【解决方案1】:

您可以map.collect 使用所需的格式:

Map fields = [class: 'blue', type:'sphere', size: 'large' ]

toKeyValue = {
    it.collect { /$it.key="$it.value"/ } join " "
}

assert toKeyValue(fields) == 'class="blue" type="sphere" size="large"'

【讨论】:

  • 如果您不需要嵌套地图,这是一个很好的解决方案。
【解决方案2】:

您可以使用 groovy 的 map.toMapString() 方法。

Map fields = [class: 'blue', type:'sphere', size: 'large' ]
fields.toMapString()

【讨论】:

  • 这不会转换为所需的格式。
  • 是的,如果它有效,那就太好了,但我仍然得到一个看起来像这样的地图:[version: 1.2.3-4] 并且它没有正确评估。由于值中的标点符号,出现意外标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2016-12-14
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
相关资源
最近更新 更多