Reputation: 25
Can anyone help to convert a list to list of Maps in Groovy ?
I have a list as below
[war, jar]
and a variable with name "value" = 2.0.0
I want to convert this into a list with maps [["pack": "war", "ver": "2.0.0"],["pack": jar, "ver": "2.0.0"]]
and create a json.
{
"ProjectId": "Projects-16",
"ChannelId": "Channels-41",
"Version": "2.0.1.0-10",
"selectedPackages": [{"pack": "war", "ver": "2.0.0"}, {"pack": jar, "ver": "2.0.0"]}]
}
Upvotes: 0
Views: 1114
Reputation: 484
Here is the solution:
import groovy.json.JsonOutput
def packages = ["war", "jar"]
def value = "2.0.0"
def list = packages.collect { [pack : it, ver : value] }
def object = [
ProjectId: "Projects-16",
ChannelId: "Channels-41",
Version: "2.0.1.0-10",
selectedPackages: list
]
def json = JsonOutput.toJson(object)
println JsonOutput.prettyPrint(json)
Each {}
entity in JSON is a map in Groovy therefore the expected [{}, {}]
is a list of maps. You need just to construct the right objects using collect with the right transformation.
Edit
I updated the solution to return the exact json output as desired using a list and the variable value
.
The output is this:
{
"ProjectId": "Projects-16",
"ChannelId": "Channels-41",
"Version": "2.0.1.0-10",
"selectedPackages": [
{
"pack": "war",
"ver": "2.0.0"
},
{
"pack": "jar",
"ver": "2.0.0"
}
]
}
Upvotes: 1