How do I use groovy jsonbuilder with .each to create an array?

Fels picture Fels · Dec 21, 2012 · Viewed 14.1k times · Source

I would like to create an array with JSON-Builder.

Expected format:

{
  "Header": {
    "SomeKey" : "SomeValue"
 }
  "Data": [
    { 
      "SomeKey" : "SomeValue"
    }, 
    {
     "SomeKey" : "SomeValue"
    }
  ]
}

My Code:

    def builder = new groovy.json.JsonBuilder()

    def root = builder {
        Header {            
        "Typ" "update"
        "Code" "UTF-8"
        "TransaktionsNr" item.transactionNumber
        "DatumZeit" new Date().format("dd.MM.yyyy HH:mm")
    }

    customers.each ({ customer->           
        "Data" { 
            "Email" customer.code
            "Newsletter" customer.newsletterSubscribed
        }
    })

However whatever I do I only get one element in the Data section. I tried using [] instead of {}, but I still only get one element, what am I doing wrong?

Answer

Will picture Will · Dec 21, 2012

That's duplicate key for JSON structure. There should not be duplicate key in the same hierarchy or they will override each other:

class Customer { String code; boolean newsletterSubscribed }

customers = [
  new Customer(code:"11111", newsletterSubscribed:true),
  new Customer(code:"22222", newsletterSubscribed:false)
]

def builder = new groovy.json.JsonBuilder()

def root = builder {
  Header {            
    "Typ" "update"
    "Code" "UTF-8"
    "TransaktionsNr" 987
    "DatumZeit" new Date().format("dd.MM.yyyy HH:mm")

  }

  customers customers.collect { customer ->
        ["Email":customer.code, 
        "Newsletter":customer.newsletterSubscribed]
    }

}

assert builder.toString() == {"Header":{"Typ":"update","Code":"UTF-8","TransaktionsNr":987,"DatumZeit":"21.12.2012 13:38"},"Data":{"Email":"22222","Newsletter":false},"customers":[{"Email":"11111","Newsletter":true},{"Email":"22222","Newsletter":false}]}