使用Lift序列化MongoRecord

时间:2011-08-18 02:16:42

标签: json scala serialization mongodb lift

我在使用Lift建立一个宁静的服务时遇到了麻烦。此时我想做的就是将MongoRecord序列化为JSON。这是我的模特:

class Team extends MongoRecord[Team] with MongoId[Team] {
  def meta = Team

  object name extends StringField(this, 100)
  object slug extends StringField(this, 100)
}

object Team extends Team with MongoMetaRecord[Team] {
  def all = Team orderAsc (_.slug) fetch()

  def apply(in: JValue): Box[Team] = Helpers.tryo{in.extract[Team]}

  def unapply(in: String): Option[Team] = Team where (_.slug eqs in) get()

  implicit def toJson(team: Team): JValue =
    Extraction.decompose(team)

  implicit def toJson(teams: Seq[Team]): JValue =
    Extraction.decompose(teams)
}

这是我对RestHelper的实现:

object TeamRestService extends RestHelper {
  serve( "api" / "teams" prefix {
    case Nil JsonGet _ => Team.all: JValue

    case Team(team) :: Nil JsonGet _ => team: JValue
  })
}

使用curl -i -H "Accept: application/json" http://localhost:8080/api/teams我获得[{}, {}]curl -i -H "Accept: application/json" http://localhost:8080/api/teams/team-1获得{}。如果我在返回单个团队或团队列表之前在TeamRestService中放置了一个print语句,我可以清楚地看到所有数据都已在Team实例上设置。出于某种原因,序列化只是返回空对象。我需要做什么才能使我的Team实例正确序列化?我是否需要制作自定义格式或使用某种TypeHint?如果是这样,我将如何做到这一点?

1 个答案:

答案 0 :(得分:2)

是的,我是傻瓜。 Extraction.decompose仅适用于案例类。 MongoRecord有一个方法asJValue。在隐式defs中使用它解决了这个问题。

implicit def toJson(team: Team): JValue = team.asJValue

implicit def toJson(teams: Seq[Team]): JValue = teams map { _.asJValue }