1

I need to create a JSON string in my Groovy script which has some elements that are array and some which are not. For example the below..

 {
 "fleet": {
   "admiral":"Preston",
   "cruisers":  [
      {"shipName":"Enterprise"},
      {"shipName":"Reliant"}
   ]
  }
}

I found this post but the answers either didn't make sense or didn't apply to my example.

I tried the below in code...

 def json = new groovy.json.JsonBuilder()
 def fleetStr = json.fleet {
         "admiral" "Preston"
         cruisers {
            {shipName: "[Enterprise]"},  {shipName: "[Reliant]"}
       }
   }

But it gives an exception...

 Ambiguous expression could be either a parameterless closure expression or an isolated open code block

1 Answer 1

2

In Groovy, the {} syntax is used for closures. For objects in JSON, you want to use the map syntax [:], and for lists, the list syntax []:

def json = new groovy.json.JsonBuilder()
def fleetStr = json.fleet {
    "admiral" "Preston"
    cruisers( [
        [shipName : "[Enterprise]"],
        [shipName: "[Reliant]"]
    ])
}

assert json.toString() == 
    '{"fleet":{"admiral":"Preston","cruisers":[{"shipName":"[Enterprise]"},{"shipName":"[Reliant]"}]}}'

Update: as per your follow-up, you need to use the same list syntax [] outside the "[Enterprise]" and "[Reliant]" strings:

def json = new groovy.json.JsonBuilder()
def fleetStr = json.fleet {
    "admiral" "Preston"
    cruisers( [
        [shipName : ["Enterprise"]],
        [shipName: ["Reliant"]]
    ])
}

assert json.toString() == 
    '{"fleet":{"admiral":"Preston","cruisers":[{"shipName":["Enterprise"]},{"shipName":["Reliant"]}]}}'
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, just a follow up question (somewhat unrelated). Supposing I wanted the value of shipName to appear as an array element in the JSON even though it can have only value. For example "shipName": ["Enterprise"], can you also help with how I can do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.