scala json验证无法正常工作

时间:2015-04-27 13:55:09

标签: json scala validation playframework-2.0

我正在关注** Play For Scala **以验证和解析Json

我在控制器中收到请求后将其转换为JsValue,就像这样

 val jsonRequest = request.body.asJson.get

我试图像这样验证它

jsonRequest.validate[ReadArtWorkCaseClass].fold(

valid = {    
          readArtWorkCaseClass =>
            log.info("valid block")

          Ok("validation successful" )
         },     
invalid = {
           log.info("invalid block")
           errors => {               
             log.info("error block")
             BadRequest(JsError.toFlatJson(errors))
            }           
          }                    
        )

我已经实现了Read for this

case class ReadArtWorkCaseClass(artworkid :String,
                                artistid :String,
                                institutionid :String ,
                                status :String,
                                groupactivityid:String,
                                details:String,
                                pricehistoryid :String,
                                sku :String,
                                dimensions :String,
                                artworkname :String,
                                artworkseries :String ,
                                workclassifier :String ,
                                genreid :String,
                                artworktype :String,
                                createddate:String)
    object ReadArtWorkCaseClass {

   implicit val artworkReads: Reads[ReadArtWorkCaseClass] = (
(JsPath \ "artWorkid").read[String] and
(JsPath \ "artistid").read[String] and
(JsPath \ "institutionid").read[String] and
(JsPath \ "activationStatus").read[String] and
(JsPath \ "groupactivityid").read[String] and
(JsPath \ "details").read[String] and
(JsPath \ "pricehistoryid").read[String] and
(JsPath \ "sku").read[String] and
(JsPath \ "dimensions").read[String] and
(JsPath \ "artworkname").read[String] and
(JsPath \ "artworkseries").read[String] and
(JsPath \ "workclassifier").read[String] and
(JsPath \ "genreid").read[String] and
(JsPath \ "artworktype").read[String] and
(JsPath \ "createddate").read[String]
)(ReadArtWorkCaseClass.apply _)
}

当我尝试通过输入空字段来验证jsonrequest时,它不会进入无效块而是运行有效块

请指导我,我的错误是什么

1 个答案:

答案 0 :(得分:1)

(JsPath \ "artWorkid").read(minLength[String](1))

它对我有用