JSON:如何根据另一个字段的值验证字段

时间:2013-02-20 22:25:54

标签: playframework-2.1

我有一个班级

/**
 * 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

0 个答案:

没有答案