我的标准查询结果如下:
[
[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来实现这种复杂的结构?
答案 0 :(得分:2)
所以,给定:
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
:
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"
}
]
}
]
}
]
}
}