简体   繁体   中英

Can I write Json from two model without transformers in Play Framework 2.4

I have two model classes

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

and i want write Json

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

without Json transformers .

now I have

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)
  )

Is there a possibility to write into the write stream multiple objects? And what about "one field" model class? Can i write custom Write , are there any workarounds?

it's a simple question if you forget about all sorts of transformers and more common terms and see in the JsObject source.

++ , - , + , deepMerge that's all you need.

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

And for "one field" model class:

case class NotificationSettings(notifications: Seq[Notification])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM