11

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?

Fels
  • 1,214
  • 2
  • 13
  • 27
  • I should add that I have to use each or to be precise a closure that gets the objects from a database: 'eachItem("customer", { customer ->' – Fels Dec 21 '12 at 15:32

1 Answers1

6

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}]}
Community
  • 1
  • 1
Will
  • 14,348
  • 1
  • 42
  • 44
  • Thanks. I was afraid I have to do something like this. The problem is I'm using this on 1.5m customers and there are more fields than in my example. I don't think I can hold all this in memory, so I guess I have to write my own json writer. But thanks anyway. – Fels Dec 21 '12 at 15:56
  • 1
    What about StreamingJsonBuilder(http://groovy.codehaus.org/gapi/groovy/json/StreamingJsonBuilder.html)? – Will Dec 21 '12 at 16:04
  • 1
    Thanks, I didn't even know about that. I *should* be able to have the whole customer list in memory if I don't have to have the whole JSON structure as well. Now it wouuld be perfect if anyone knew how to export this without the need to have all the data in a list before the export :) – Fels Dec 21 '12 at 18:20