我试图弄清楚如何在我的 Scala 项目中正确序列化来自 MongoDB 的文档。我在这里遇到的问题是,当我的文档中有一个 Array 字段以及如何在 Scala 中处理它时,我不确定该怎么做。这是文档在 MongoDB 中的样子:
> db.injuries.findOne()
{
"_id" : ObjectId("5220ef71bbf8af333d000001"),
"team_id" : 86,
"league" : "NFC",
"team_name" : "Arizona Cardinals",
"players" : [
{
"player_id" : 9864,
"date" : "8/26/2013",
"position" : "TE",
"name" : "Rob Housler",
"injury" : "is doubtful for 9/8 against St. Louis",
"status" : "Doubtful",
"fantasy" : "",
"injured" : "True",
"type" : "ankle"
},
{
"player_id" : 11610,
"date" : "8/25/2013",
"position" : "G",
"name" : "Jonathan Cooper",
"injury" : "may be placed on injured reserve",
"status" : "Out",
"fantasy" : "",
"injured" : "True",
"type" : "leg"
},
{
"player_id" : 9126,
"date" : "4/3/2013",
"position" : "LB",
"name" : "Daryl Washington",
"injury" : "will be eligible to return on 10/6 against Carolina",
"status" : "Suspended",
"fantasy" : "",
"injured" : "True",
"type" : "four-game suspension"
}
],
"updated_at" : ISODate("2013-08-30T19:16:01.466Z"),
"created_at" : ISODate("2013-08-30T19:16:01.466Z")
}
>
现在我需要创建一个案例类,以便我可以为该文档创建一个自定义序列化程序并将其交付给客户端。我开始构建一个案例类,如下所示:
case class Injury(_id: ObjectId = new ObjectId, team_id: Int, team_name: String, league: String, players: List[????], created_at: Option[Date] = None, updated_at: Option[Date] = None, id: Option[ObjectId] = None )
我不一定要创建一个播放器案例类,因为播放器哈希在其他集合中看起来不同,具体取决于上下文。我可能有一个球员数组来表示“时间表”集合,我不会在那里列出伤病数据。它不是对玩家集合的实际引用,它只是一个带有哈希的列表,其中字段被命名为“玩家”。理想情况下,我可以弄清楚如何编写一个序列化,它会在请求该团队的 ID 时简单地输出:
{
"team_id": 86,
"team_name": "Arizona Cardinals",
"players": [
{
"player_id": 9864,
"date": "8/26/2013",
"position": "TE",
"name": "Rob Housler",
"injury": "is doubtful for 9/8 against St. Louis",
"status": "Doubtful",
"fantasy": "",
"injured": "True",
"type": "ankle"
},
{
"player_id": 11610,
"date": "8/25/2013",
"position": "G",
"name": "Jonathan Cooper",
"injury": "may be placed on injured reserve",
"status": "Out",
"fantasy": "",
"injured": "True",
"type": "leg"
},
{
"player_id": 9126,
"date": "4/3/2013",
"position": "LB",
"name": "Daryl Washington",
"injury": "will be eligible to return on 10/6 against Carolina",
"status": "Suspended",
"fantasy": "",
"injured": "True",
"type": "four-game suspension"
}
]
}
为了能够导出最终的 JSON 文档,我还需要做什么?我知道 Salat 可以处理 case 类的序列化。但我不确定如何在这里处理 player 属性。这是我开始研究的序列化程序的开始,但仍然不知道如何将玩家地图放入此处:
class InjurySerializer extends CustomSerializer[Injury](format => ({
case JObject(
("id", JString(id)) ::
("team_id", JString(team_id)) ::
("team_name" , JString(team_name)) ::
("league" , JString(league)) :: Nil) =>
Injury(new ObjectId, team_id.asInstanceOf[Int], team_name.asInstanceOf[String], league.asInstanceOf[String])
}, {
case injury: Injury =>
JObject.apply(
"team_id" -> JInt(injury.team_id),
"team_name" -> JString(injury.team_name),
"league" -> JString(injury.league)
)
}))
然后我有一个简单的助手来检索所有文档:
object Injury {
def findAll = {
val results = InjuryDAO.findAll
results.map(grater[Injury].asObject(_)).toList
}
}
这很好用,但不包括上面建议的玩家地图。