Kush Arora
Kush Arora

Reputation: 11

JSON structure string in groovy

I wanted to create a string in groovy in following structure

"{\"Changes\": [{\"Action\": \"UPSERT\", \"ResourceRecordSet\": 
       { \"Name\": \"rms-collector-demo.cnqr.delivery.\",\"Type\": 
         \"CNAME\",\"TTL\": 300,\"ResourceRecords\": [{ \"Value\": 
         \"d-4kushcom5y13.execute-api.us-west-2.amazonaws.com\"}]}}]}"

tried with escaping characters but was not useful. can some one help what should be the format used in groovy to define this string.

Upvotes: 1

Views: 95

Answers (2)

cfrick
cfrick

Reputation: 37008

Instead of carefully crafting some JSON as a string (and maybe add errors in the process), you can use JsonOutput to create the JSON from a simple data structure:

def json = groovy.json.JsonOutput.toJson([Changes: ["X"]])
println json
// => {"Changes":["X"]}

Upvotes: 0

ernest_k
ernest_k

Reputation: 45309

Groovy supports multi-line strings, so you can simply use

"""
   {"Changes": [{"Action": "UPSERT", "ResourceRecordSet": 
   { "Name": "rms-collector-demo.cnqr.delivery.","Type": 
     "CNAME","TTL": 300,"ResourceRecords": [{ "Value": 
     "d-4kushcom5y13.execute-api.us-west-2.amazonaws.com"}]}}]}
"""

You can also use ''' to create a normal String.

Upvotes: 1

Related Questions