【问题标题】:Serialize a MongoRecord using Lift使用 Lift 序列化 MongoRecord
【发布时间】:2011-10-29 10:08:55
【问题描述】:

我在使用 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" @987654321@ 得到[{}, {}],使用curl -i -H "Accept: application/json" @987654322@ 得到{}。如果我在返回单个团队或团队列表之前在TeamRestService 中添加一个打印语句,我可以清楚地看到所有数据都已设置在 Team 实例上。出于某种原因,序列化只是返回空对象。我需要做什么才能使我的 Team 实例正确序列化?我是否需要制作自定义格式或使用某种 TypeHint?如果是这样,我该怎么做?

【问题讨论】:

    标签: json scala serialization mongodb lift


    【解决方案1】:

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

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

    【讨论】:

    • teams map ( _.asJValue ) 给你一个Seq[JValue] 因此你会想要JArray(teams map ( _.asJValue ))
    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2013-12-27
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多