gpt4 book ai didi

arrays - 如何使用带有 .each 的 groovy jsonbuilder 创建数组?

转载 作者:行者123 更新时间:2023-12-04 02:19:13 25 4
gpt4 key购买 nike

我想用 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
}
})

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

最佳答案

这是 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}]}

关于arrays - 如何使用带有 .each 的 groovy jsonbuilder 创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com