使用Salat和Scala为嵌入式MongoDB数组创建案例类

时间:2013-08-30 21:24:16

标签: json scala scalatra salat json4s

我试图弄清楚如何在我的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类,以便为这个文档创建一个自定义序列化程序并将其传递给客户端。我开始构建一个类似于以下的案例类:

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可以处理序列化到案例类..但我不知道如何处理这里的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
  }

}

这很好,但不包括上面建议的球员地图。

2 个答案:

答案 0 :(得分:0)

不支持数组。使它成为一个列表,一个seq,几乎任何其他类型的集合,您的文档将正确序列化和反序列化。

https://github.com/novus/salat/wiki/Collections

制作一个包含所有可能字段的玩家案例类,并使用默认参数来涵盖所有案例。

如果有太多不同的案例可以覆盖,那就是事情变得非常丑陋。你本质上是试图反序列化没有预期结构的数据......究竟是什么?我没有为主流Salat添加Map[String, Any]支持,尽管有一个出色的拉动请求。

答案 1 :(得分:0)

你可能必须在这里使用一些自定义序列化程序,我假设你有一个父对象的句柄 - 让我们称之为伤害

 val playerRefs = injury.get("palyers")
 var obj = MongoDBObject("list" -> playerRefs )
 obj.as[MongoDBList]("list").toList.foreach {
   value =>
        val playerDef = value.asInstanceOf[BasicDBObject]
        // Access values from player -
        val name = playerDef.get("name")asInstanceOf[String]
        // Build your case class 
  }