我想问一个关于Play中JSON验证最简洁方法的问题!框架
在官方Play教程中,我找到了有关JSON Macro Inception的主题。它的序列化/反序列化的主要想法看起来很不错:
import play.api.libs.json._
case class Person(name: String, age: Int)
object Person{
implicit val personFmt = Json.format[Person]
}
但是如果我想在这里提出一些验证限制呢?例如,我想接受18至60岁的年龄?在这种情况下,我应该返回标准Writes
和Reads
吗?
由于
答案 0 :(得分:3)
如果您想保留所有验证错误,是的。 Reads似乎有filter
和filterNot
个函数,您可以在其中添加自己的验证错误,但它们最终会像定义Reads
一样冗长方式:
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class Person(name: String, age: Int)
object Person{
implicit val personFmt: Reads[Person] = (
(__ \ "name").read[String] and
(__ \ "age").read[Int](Reads.min(18) keepAnd Reads.max(60))
)(Person.apply _)
}
我通常会使用上面更详细的样式来定义我的Reads
,使用Writes
宏定义Json.writes[T]
,因为我通常不需要限制返回的内容客户。
答案 1 :(得分:1)
我认为您正在寻找JSON combinators。例如,您可以按如下方式验证Person实例:
implicit val PersonReads : Reads[Person] = (
(JsPath \ "name").read[String] and
(JsPath \ "age").read[Int](min(18) keepAnd max(60))
)(Person.apply _)
您还可以定义用于隐式转化的自定义Format[Person]
以及Reads[Person]
和Writes[Person]
的混合:
val personReads: Reads[Person] = (
(JsPath \ "name").read[String] and
(JsPath \ "age").read[Int](min(18) keepAnd max(60))
)(Person.apply _)
val personWrites: Writes[Person] = (
(JsPath \ "name").write[String] and
(JsPath \ "age").write[Int]
)(unlift(Person.unapply))
implicit val personFormat: Format[Person] =
Format(personReads, personWrites)