【问题标题】:How to read and write Anorm object with the new JSON API in Play Framework 2.1-RC2?如何在 Play Framework 2.1-RC2 中使用新的 JSON API 读写 Anorm 对象?
【发布时间】:2012-12-29 06:19:44
【问题描述】:

我正在尝试将我的 Play 2.0.x 应用程序迁移到 Play 2.1-RC2 并偶然发现了以下问题。在我的应用程序中,我有一个看起来像这样的案例类:

case class Player(
  playerId: Pk[Long],
  name: Option[String],
  groupId: Long
)

在我的 Play 2.0.x 代码中,我有一个 PlayerFormat 对象,用于读取和写入此类的 JSON 实例,如下所示:

object PlayerFormat extends Format[Player] {

def reads(json: JsValue): Player = Player(
    (json \ "id").asOpt[Long].map( Id(_) ).getOrElse( NotAssigned ),
    (json \ "name").asOpt[String],
    (json \ "group" \ "id").as[Long]
)

def writes(p: Player): JsValue = toJson(
  Map(
      "id" -> toJson(p.playerId.toOption),
      "name" -> toJson(p.name),
      "group" -> toJson(
          Map("id" -> p.groupId)
      )    
  )
)

}

问题是“我如何在 Play 2.1 中读取可选(可为空)属性“id”并根据其存在将 playerId 属性设置为 Id[Long]NotAssigned

另外,这是否可以通过某种方式重写以使用 JSON inception 宏?

【问题讨论】:

    标签: json scala playframework-2.0 anorm playframework-2.1


    【解决方案1】:

    Json Macro Inception 在这里不是一个好的选择,因为这种情况太复杂了。只支持经典案例,不能map值举例。

    在这种情况下,您需要特定的格式化程序

    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import anorm._
    
    implicit val playerFormat = (
        (__ \ "id").formatNullable[Long] and
        (__ \ "name").formatNullable[String] and
        (__ \ "group" \ "id").format[Long]
    )((id, name, group) => Player(id.map(Id(_)).getOrElse(NotAssigned), name, group), 
      (p: Player) => (p.playerId.toOption, p.name, p.groupId))
    

    这有点复杂,因为您的要求是 ;)

    【讨论】:

    • 感谢 Julien,这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2020-01-14
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多