Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 766
Fels Avatar asked Dec 21 '12 15:12

Fels


1 Answers

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}]}
like image 180
Will Avatar answered Nov 16 '22 02:11

Will