Aydin
Aydin

Reputation: 331

Can I put conditional expressions inside multi-line strings in groovy?

For example, given the following:

"""
 {
   "a": "$a",
   "b": "$b",
   "c": "$c"
 }
"""

How can I stop it from including the last line ("c":"$c") if $c is null?

Upvotes: 4

Views: 1227

Answers (2)

tim_yates
tim_yates

Reputation: 171084

Or, as you're writing json;

def map = [a:a, b:b] + (c != null ? [c:c] : [:])
String json = new groovy.json.JsonBuilder(​​​​​​​​​map)​

Upvotes: 2

Igor Artamonov
Igor Artamonov

Reputation: 35961

That's going to be not so nice looking:

"""
     {
       "a": "$a",
       "b": "$b"${c != null ? ',\n       "c": "' + c + '"' : '' }
     }
"""

this if you need same formatting.

Or else, in more readable form:

"""
 {
   "a": "$a",
   "b": "$b"
   ${c != null ? ', "c": "' + c + '"' : '' }
 }
"""

Upvotes: 2

Related Questions