gpt4 book ai didi

json - Groovy:将数组转换为JSon

转载 作者:行者123 更新时间:2023-12-02 14:15:01 24 4
gpt4 key购买 nike

Groovy是新手,无法将数组转换为JSON。计算出的JSON应该具有我数组列表中的所有值,但它仅存储最后一个。这是代码:

def arraylist = [["0",2],["1",8],["2",6],["3",8],["4",3]]

def arraysize = arraylist.size()

def builder = new groovy.json.JsonBuilder()
builder ({
cols([
{
"id" "hours"
"label" "Hours"
"type" "string"
},
{
"id" "visitor"
"label" "Visitors"
"type" "number"
}
])

rows([
{
for( i in 0..< arraysize )
{
c([
{
"v" arraylist[i][0]
},
{
"v" arraylist[i][1]
}
])
}//for

}
])
})

println builder.toPrettyString()

可以尝试在此处运行代码:
http://groovyconsole.appspot.com/

预期的输出在这里:
{
"cols": [
{
"id": "hours",
"label": "Hours",
"type": "string"
},
{
"id": "visitor",
"label": "Visitors",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "0"
},
{
"v": 2
}
]
},
{
"c": [
{
"v": "1"
},
{
"v": 8
}
]
},
{
"c": [
{
"v": "2"
},
{
"v": 6
}
]
},
{
"c": [
{
"v": "3"
},
{
"v": 8
}
]
},
{
"c": [
{
"v": "4"
},
{
"v": 3
}
]
}
]
}

最佳答案

这样的事情似乎可以提供您想要的结果:

def arraylist = [["0",2],["1",8],["2",6],["3",8],["4",3]]

def builder = new groovy.json.JsonBuilder()
builder {
cols( [
[ id: "hours", label: "Hours", type: "string" ],
[ id: "visitor", label: "Visitors", type: "number" ] ] )

rows( arraylist.collect { pair -> [ c: pair.collect { item -> [ v: item ] } ] } )
}

println builder.toPrettyString()

关于json - Groovy:将数组转换为JSon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739152/

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