播放Json单场读取验证器

时间:2015-04-12 03:01:50

标签: json scala playframework playframework-2.0

我试图在Play中为传入的Json添加简单验证。基于this question,我尝试写作:

case class ApiData(data: String)

def maxLengthValidator = Reads.StringReads.filter(ValidationError("Error"))(_.length < 100)

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator)
)(ApiData.apply _)

这不会编译,产生错误:

type mismatch;
[error]  found   : String => ApiData
[error]  required: play.api.libs.json.Reads[?]
[error]     )(ApiData.apply _)
[error]                        ^
[error] one error found

但如果我添加第二个字段,它会编译:

case class ApiData(data: String, __doNotUse: Option[Int])

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator) and
  (JsPath \ "__doNotUse").readNullable[Int]
)(ApiData.apply _)

如果只使用一个字段,我需要做什么?

1 个答案:

答案 0 :(得分:6)

由于您只有一个字段,因此您不需要使用组合子语法来创建读取,您只需使用Reads上已定义的函数来构建所需的函数。

def maxLengthValidator = Reads.of[String].filter(ValidationError("Error"))(_.length < 100)

case class ApiData(data: String)

object ApiData {

  implicit val reads: Reads[ApiData] = (__ \ "data").read(maxLengthValidator).map(ApiData.apply _)

}

您从Reads[String]开始,添加一些验证(filter),然后将有效结果转换为您自己的富类型(map)。