我有一个像这样的案例对象列表:
AppInfo(client = "client1", project = "project1", version = "version1")
AppInfo(client = "client1", project = "project1", version = "version2")
AppInfo(client = "client2", project = "project3", version = "version1")
AppInfo(client = "client2", project = "project4", version = "version1")
并且需要创建一个这样的嵌套结构:
Map(
"clients" -> List(
Map(
"name" -> "client1",
"projects" -> List(
Map(
"name" -> "project1",
"versions" -> List(
"version1",
"version2"
)
)
)
),
Map(
"name" -> "client2",
"projects" -> List(
Map(
"name" -> "project3",
"versions" -> List(
"version1"
)
),
Map(
"name" -> "project4",
"versions" -> List(
"version1"
)
)
)
)
)
)
这看起来很糟糕,但它将序列化为这个非常简单的JSON:
{
"clients": [
{
"name": "client1",
"projects": [
{
"name": "project1",
"versions": [
"version1",
"version2"
]
}
]
},
{
"name": "client2",
"projects": [
{
"name": "project3",
"versions": [
"version1"
]
},
{
"name": "project4",
"versions": [
"version1"
]
}
]
}
]
}
有没有合理的方法来做到这一点?现在我在列表中的groupBys中的地图中有地图.
编辑
像Clojure的Specter库可能会有所帮助.
最佳答案 怎么样:
for {
(clientName, clientInfos) <- infoList.groupBy(_.client)
} yield {
val clientProjects = clientInfos.groupBy(_.project)
val projectSection = clientProjects.map { case(name, infos) => Map("name" -> name, "versions" -> infos.map(_.version)) }
Map("name" -> clientName, "projects" -> projectSection)
}
它不会减少map或groupBy调用的数量,但这是我能够组织代码的最方便的方式.