2

我有一堂课

/**
 * If stub == true data == length of the binary data
 * If stub == false data == binary data
 */
case class Attachment(contentType: String,
                      stub: Boolean,
                      data: Either[Int, Array[Byte]])

我正在尝试Format为它写一个:

implicit val attachmentFormat = new Format[Attachment] {

    def reads(json: JsValue): JsResult[Attachment] = (
      "content_type".read[String] ~
      "stub".read[Boolean] ~
      /// ??? How do i validate data based on the value of stub
    )(Attachment.apply)

    def writes(o: Attachment): JsValue = obj(
      "content_type" -> toJson(o.contentType),
      "stub" -> toJson(o.stub),
      "data" -> o.data.fold(
        length => toJson(length),
        bytes => toJson(new String(Base64.encode(bytes)))
      )
    )
  }

我可以进行有条件的写入,data但我不明白如何data根据stub.

4

0 回答 0