5

我正在浏览: http ://www.playframework.com/documentation/2.1.1/ScalaJsonCombinators并搜索如何在进行读写时排除值。它可能在那里,但我找不到它。

所以假设我有一个案例类 Booking ,它有一堆参数、一个creationTimebookingId。当从对象写入 Json 时,我想写入所有参数但是当从 Json 读取对象时,例如在我的控制器中创建 POST 时:

def createBooking = Action(parse.json) {
    implicit request => {
      request.body.validate[Booking].map {
        case (booking) => {
          Logger.info("" + booking)
          Ok("ONLY TEST")
        }
      }.recoverTotal {
        e => BadRequest("Detected error:" + JsError.toFlatJson(e))
      }
    }
  }

我不想在 Json POST 中提供值creationTimebookingId,我不想用我的 Reads impl 读取值:

package models.booking

import java.util.UUID
import org.joda.time.{DateTime}
import play.api.libs.functional.syntax._
import play.api.libs.json._

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

  def accepted(): Booking = {
    this.copy(status = BookingState.ACCEPTED)
  }

  def sent(): Booking = {
    this.copy(status = BookingState.SENT)
  }

  def denied(): Booking = {
    this.copy(status = BookingState.DENIED)
  }

  def denyWithNewTimeSuggestion(): Booking = {
    this.copy(status = BookingState.DENIED_NEW_TIME_SUGGESTED)
  }

  def timeout(): Booking = {
    this.copy(status = BookingState.TIMED_OUT)
  }

  def sendOnOpening(): Booking = {
    this.copy(status = BookingState.ON_HOLD)
  }
}

object Booking {

  implicit object UUIDFormat extends Format[UUID] {
    def writes(uuid: UUID): JsValue = JsString(uuid.toString())
    def reads(json: JsValue): JsResult[UUID] = json match {
      case JsString(x) => JsSuccess(UUID.fromString(x))
      case _ => JsError("Expected UUID as JsString")
    }
  }

  val pattern = "yyyy-M-dd"
  implicit val dateFormat =
    Format[DateTime](Reads.jodaDateReads(pattern), Writes.jodaDateWrites(pattern))

  import utils.EnumUtils.enumReads
  implicit val bookingStateReads = enumReads(BookingState)

  import play.api.libs.json.Reads._
  implicit val bookingReads: Reads[Booking] = (
    (__ \ "bookingId").read[UUID] and
      (__ \ "rId").read[Long] and
      (__ \ "creationTime").read[DateTime] and
      (__ \ "user").read[User] and
      (__ \ "dateTime").read[BookingTime] and
      (__ \ "numOfGuest").read[Int] and
      (__ \ "status").read[BookingState.BookingState]
    )(Booking.apply _)

  import utils.EnumUtils.enumWrites

  import play.api.libs.json.Writes._
  implicit val bookingWrites: Writes[Booking] = (
    (__ \ "bookingId").write[UUID] and
      (__ \ "rId").write[Long] and
      (__ \ "creationTime").write[DateTime] and
      (__ \ "user").write[User] and
      (__ \ "dateTime").write[BookingTime] and
      (__ \ "numOfGuest").write[Int] and
      (__ \ "status").write[BookingState.BookingState]
    )(unlift(Booking.unapply))
}

object BookingState extends Enumeration {
  type BookingState = Value
  val NEW = Value("NEW")
  val SENT = Value("SENT")
  val ACCEPTED = Value("ACCEPTED")
  val DENIED = Value("DENIED")
  val DENIED_NEW_TIME_SUGGESTED = Value("DENIED_NEW_TIME_SUGGESTED")
  val TIMED_OUT = Value("TIMED_OUT")
  val ON_HOLD = Value("ON_HOLD")
}

如何指定customBookingReads排除值bookingIdcreationTime。我还想保留原始的“bookingReads”,以便我可以将其用于其他事情。

4

2 回答 2

0

我认为获得所需内容的最直接方法是制作bookingIdandcreationTime字段Option

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

这样您reads仍然可以尝试阅读这些字段,但如果它们丢失,它们将只是None. 我做了这件事,它运行良好,即使使用标准Json.format[Booking]- 不需要自定义代码。

于 2015-01-06T07:38:42.567 回答
0

经过一番深思熟虑后,我意识到在这种情况下,预订和请求实际上是两个不同的东西,因此我不应该尝试将这两者混为一谈。

我创建了一个 BookingRequest,可以从中创建一个 Booking。

预约申请:

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

控制器:

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

但是我仍然很好奇在进行读写时如何排除值

于 2013-05-31T07:54:28.193 回答