title: How to Generate an Array of Objects with Nested Siblings with Groovy JsonBuilder
body: <p>I'm trying to generate a JSON array with multiple nested objects.</p>
  
  <p><strong>Here's what I'd like to generate:</strong> (shortened output since I want an array, this just repeats if you run the code):</p>
  
  <pre><code>[
      {
          "User": {
              "Name": "Foo",
              "Email": "test@example.com"
          },
          "Details": {
              "Address": {
                  "City": "Anywhere",
                  "Country": "USA",
                  "State": "ID",
                  "ZipCode": "55842"
              },
              "FavoriteColor": "Blue"            
          }
      }
  ]
  
  </code></pre>
  
  <p><strong>Instead I'm generating this:</strong></p>
  
  <pre><code>[
          {
              "User": {
                  "Name": "Foo",
                  "Email": "test@example.com"
              },
              "Address": {
                  "City": "Anywhere",
                  "Country": "USA",
                  "State": "ID",
                  "ZipCode": "55842"
              },
              "Details": [
                  {
                      "FavoriteColor": "Blue"
                  },
                  {
                      "City": "Anywhere",
                      "Country": "USA",
                      "State": "ID",
                      "ZipCode": "55842"
                  }
              ]
          }
      ]
  </code></pre>
  
  <p><strong>Here's my code:</strong></p>
  
  <pre><code>def array = 1..3
  
  def builder = new groovy.json.JsonBuilder()
  builder array.collect { itemNumber -&gt;
      [{
          User(
              Name: "Foo" + itemNumber,
              Email: "test@example.com"
          )
          Details(
              Address(
                  City: "Anywhere",
                  Country: "USA",
                  State: "ID",
                  ZipCode: "55842"
              ),
              FavoriteColor: "Blue"
          )
      }
      ]
  }
  
  println groovy.json.JsonOutput.prettyPrint(builder.toString())
  </code></pre>