Groovy 使用json映射到具有特定键的列表
我已经设法从json列表中取出一个json,并从json中取出一个密钥 我正在研究如何将每个版本值放入列表中。如何从地图上做到这一点Groovy 使用json映射到具有特定键的列表,groovy,Groovy,我已经设法从json列表中取出一个json,并从json中取出一个密钥 我正在研究如何将每个版本值放入列表中。如何从地图上做到这一点 Map convertedJSONMap = new JsonSlurperClassic().parseText(data) //If you have the nodes then fetch the first one only if(convertedJSONMap."items"){ println "Version : " + convert
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)
//If you have the nodes then fetch the first one only
if(convertedJSONMap."items"){
println "Version : " + convertedJSONMap."items"[0]."version"
}
所以我需要的是某种foreach循环,它将抛出地图并获取项目。从每个版本中选择一个版本,并将其放入列表中。怎么做 Groovy有一个可用于将一种类型的值列表转换为新值列表的函数。考虑下面的例子:
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items.collect { it.version }
println list.inspect()
输出:
['1.23', '1.14.0', '2.11', '8.0', '2.32', '4.11.2.3']
Groovy还提供了可以将此示例简化为以下内容的功能:
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items*.version
println list.inspect()
甚至这个(您可以用.version
替换.version
):
所有示例都产生相同的输出。绝对完美的答案。谢谢
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items.version
println list.inspect()