S.Dan
S.Dan

Reputation: 1902

How to set String array from variable in Groovy

I have the following piece of code:

String[] arr = [
            "Cat",
            "Dog",
            "Horse"
    ]

String payload = """
{
    "Data" : ${arr}
}
"""

My end goal is to obtain a payload as:

{"Data":["Cat", "Dog", "Horse"]}

But the result I get is:

{"Data":[Cat, Dog, Horse]}

How can I fix this?

Upvotes: 1

Views: 121

Answers (2)

injecteer
injecteer

Reputation: 20699

The groovy way would be simply

String[] arr = [
            "Cat",
            "Dog",
            "Horse"
    ]
String payload = groovy.json.JsonOutput.toJson( Data:arr )

assert '{"Data":["Cat","Dog","Horse"]}' == payload

Upvotes: 0

S.Dan
S.Dan

Reputation: 1902

So I had been doing it wrong and found the solution using the help of a friend:

String payload = """
{
    "Data" : ${JsonOutput.toJson(arr)}
}
"""

Upvotes: 1

Related Questions