How do I exclude values when doing json Reads and Writes in my Play2 scala application How do I exclude values when doing json Reads and Writes in my Play2 scala application json json

How do I exclude values when doing json Reads and Writes in my Play2 scala application


After some soul searching I realised that in this case the Booking and the Request is actually two different things, therefore I shouldn't try mixing those two.

I created a BookingRequest from which a Booking could be created.

BookingRequest:

case class BookingRequest(rId: Long,                          user: User,                          bookingTime: BookingTime,                          numOfGuest: Int) {  def createBooking(): Booking = {    Booking(UUID.randomUUID(), this.rId, new DateTime(), this.user, this.bookingTime, this.numOfGuest, BookingState.NEW)  }    }object BookingRequest {  import play.api.libs.json.Reads._  implicit val bookingRequestReads: Reads[BookingRequest] = (    (__ \ "rId").read[Long] and      (__ \ "user").read[User] and      (__ \ "bookingTime").read[BookingTime] and      (__ \ "numOfGuest").read[Int]    )(BookingRequest.apply _)  import play.api.libs.json.Writes._  implicit val bookingRequestWrites: Writes[BookingRequest] = (    (__ \ "rId").write[Long] and      (__ \ "user").write[User] and      (__ \ "bookingTime").write[BookingTime] and      (__ \ "numOfGuest").write[Int]    )(unlift(BookingRequest.unapply))    }

Controller:

def createBooking = Action(parse.json) {    implicit request => {      request.body.validate[BookingRequest].map {        case (bookingRequest) => {          Logger.info("Booking" + bookingRequest)          Logger.info("BookingRequest" + bookingRequest.createBooking())          // SAVE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!          Ok(Json.obj("status" -> "OK"))        }      }.recoverTotal {        e =>  BadRequest(Json.obj("status" ->"KO", "message" -> JsError.toFlatJson(e)))      }    }  }

But I'm still curious how to exclude values when doing Reads and Writes


I think the most straightforward way of getting what you want is to make the bookingId and creationTime fields Options.

case class Booking (bookingId: Option[UUID],                        rId: Long,                        creationTime: Option[DateTime],                        user: User,                        dateTime: BookingTime,                        numOfGuest: Int,                        status: BookingState.BookingState)

This way your reads can still try to read those fields, but if they're missing they'll just be None. I do this exact thing and it works well, even with a standard Json.format[Booking] -- no custom code required.