我在使用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?如果是这样,我将如何做到这一点?
答案 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 }