gpt4 book ai didi

json - 如何将 map 列表转换为常规的groovy/grails对象?

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

我从标准查询中得到了这样的结果:

[
[id:79, accountName:a99name, layoutPathId:40, layoutPath:/etc/test.txt, dataTypeId:5, dataType:demo1, vendorId:34, vendorName:v21],
[id:79, accountName:a99name, layoutPathId:41, layoutPath:/etc/test1.txt, dataTypeId:5, dataType:demo1, vendorId:34, vendorName:v21],
[id:79, accountName:a99name, layoutPathId:42, layoutPath:/etc/test3.txt, dataTypeId:6, dataType:demo2, vendorId:35, vendorName:v22]
]

现在,我想将此结果集转换为JSON结构,如下所示:
    {
"account": {
"id": 76,
"name": "a99name",
"datatypes": [
{
"id": 5,
"name": "demo1",
"vendors": [
{
"id": 34,
"name": "v22",
"layouts": [
{
"layoutPath": "/etc/test3.txt",
"id": "42"
},
....
]
},
......
]
},
.......
]
}
}

我可以使用DTO,但从长远来看,我会制作很多DTO类。
有没有更简单的方法可以单独使用java和groovy来实现这种复杂的结构?

最佳答案

因此,鉴于:

def input = [
[id:79, accountName:'a99name', layoutPathId:40, layoutPath:'/etc/test.txt', dataTypeId:5, dataType:'demo1', vendorId:34, vendorName:'v21'],
[id:79, accountName:'a99name', layoutPathId:41, layoutPath:'/etc/test1.txt', dataTypeId:5, dataType:'demo1', vendorId:34, vendorName:'v21'],
[id:79, accountName:'a99name', layoutPathId:42, layoutPath:'/etc/test3.txt', dataTypeId:6, dataType:'demo2', vendorId:35, vendorName:'v22']
]

您可以执行这种“手动”数据操作:
def munged = [ account: [
id: input.id.head(),
name: input.accountName.head(),
dataTypes: input.groupBy({it.dataTypeId}).collect { did, dataType ->
[ id: did,
name: dataType.dataType.head(),
vendors: dataType.groupBy {it.vendorId}.collect { vid, vendor ->
[ id: vid,
name: vendor.vendorName.head(),
layouts: vendor.groupBy { it.layoutPathId }.collect { lid, layout ->
[ id: lid,
layoutPath: layout.layoutPath.head()
]
}
]
}
]
}
]]

然后通过Groovy的 JsonBuilder传递此新 map :
println new groovy.json.JsonBuilder(munged).toPrettyString()

将打印:
{
"account": {
"id": 79,
"name": "a99name",
"dataTypes": [
{
"id": 5,
"name": "demo1",
"vendors": [
{
"id": 34,
"name": "v21",
"layouts": [
{
"id": 40,
"layoutPath": "/etc/test.txt"
},
{
"id": 41,
"layoutPath": "/etc/test1.txt"
}
]
}
]
},
{
"id": 6,
"name": "demo2",
"vendors": [
{
"id": 35,
"name": "v22",
"layouts": [
{
"id": 42,
"layoutPath": "/etc/test3.txt"
}
]
}
]
}
]
}
}

关于json - 如何将 map 列表转换为常规的groovy/grails对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32948054/

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