Scala中的Json转换/验证

时间:2015-03-01 08:41:17

标签: json validation scala playframework playframework-2.0

我正在尝试使用play 2.3中的json转换来转换和验证jsvalue,该值是可选的但如果它存在则应该传递isUrl调用,但代码不能编译...

import org.apache.commons.validator.GenericValidator
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._



def transform(js:JsValue):JsResult[JsValue]={
    val transformer: Reads[JsObject] =
        (( __ \ 'website).json.pick(Reads.optionWithNull[Option[JsString]] keepAnd filter(
          ValidationError("Website URL is not valid"))((in:String) => GenericValidator.isUrl(in))))

    transformer.reads(js).map{e=> e }
}

1 个答案:

答案 0 :(得分:0)

实现这一目标的一种方法是使用Reads,根据Play docs,它也可以充当验证者。

import play.api.libs.json._

object Test extends App {

  // defining a Reads which acts as a validator as well
  def url(implicit reads: Reads[String]): Reads[String] = 
    Reads.pattern( """\blahblah""".r, "error.url")


  val OptionalUrlFormat: Reads[Option[String]] =
    (__ \ 'website).readNullable[String](url)


  private val jsonString = "{\n  \"website\": \"http://example.com\"\n}"
  private val json = Json.parse(jsonString)
  val maybeUr = Json.fromJson(json)(OptionalUrlFormat)
  println(maybeUr.get)

}