如何使用groovy jsonbuilder和.each来创建数组?

时间:2012-12-21 15:25:40

标签: arrays groovy each jsonbuilder

我想用JSON-Builder创建一个数组。

预期格式:

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

我的代码:

    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
        }
    })

然而无论我做什么,我只在数据部分得到一个元素。我尝试使用[]而不是{},但我仍然只得到一个元素,我做错了什么?

1 个答案:

答案 0 :(得分:6)

这是JSON结构的重复键。 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}]}