我可以在Play Framework 2.4中从没有变换器的两个模型中编写Json

时间:2015-12-16 12:10:13

标签: json transform playframework-2.4

我有两个model classes

case class Calendar(id: String, summary: String)
case class ACL(account: String, role: String)

我希望写Json

{
    "id": "some id",
    "summary": "some text",
    "acl": [
        "user": "some user",
        "role": "some role"
    ]
}

没有Json transformers

现在我有

val calendar = ...
val acl = ...

val calendarWrite = (
  (__ \ "_id").write[String] and
  (__ \ "summary").write[String] 
)(unlift(Calendar.unapply))

val aclWrite = (
  (__ \ "user").write[String] and
  (__ \ "role").write[String]
)(unlift(ACL.unapply))

val updateForMongo =
        __.json.update(
            (__ \ "acl" ).json.put( 
                JsArray( Seq( aclWrite.writes(acl) ))
            )
        )

calendarWrite.writes(calendar)
  .transform(updateForMongo)
  .fold(
    invalid =>
      Future.successful(0),
    valid =>
      calendarsCollection.insert(valid).map(l => l.n)
  )

是否有可能将多个对象写入写入流? 那么“一个领域”的模型类呢?我可以编写自定义Write,有没有解决方法?

1 个答案:

答案 0 :(得分:0)

如果您忘记了各种变形金刚和更常见的术语,请参阅JsObject来源,这是一个简单的问题。

++-+deepMerge这就是您所需要的一切。

calendarWrite.writes(calendar) + ("acl" -> JsArray(Seq( aclWrite.writes(acl) )))

对于“一个领域”的模型类:

case class NotificationSettings(notifications: Seq[Notification])

val nwrite = new Writes[NotificationSettings]{
  override def writes(o: NotificationSettings): JsValue = {
    Json.obj("notifications" -> o.notifications)
  }
}