为什么我得到"应用程序不接受参数"使用JSON Read with Play framework 2.3?

时间:2015-03-31 06:26:19

标签: json scala validation playframework-2.3

我想在Play framework 2.3x中为一些Scala模型类编写JSON验证。我按照说明(https://playframework.com/documentation/2.3.x/ScalaJsonCombinators)使用JSON读取来执行此操作。但我得到了#34;应用程序没有参数"错误,我不知道如何解决这个问题。

这是我的代码。

package models

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
import reactivemongo.bson.BSONObjectID
import java.util.Date

case class ArtifactModel(
                          _id: BSONObjectID,
                          name: String,
                          createdAt: Date,
                          updatedAt: Date,
                          attributes: List[AttributeModel],
                          stateModels: List[StateModel])

case class AttributeModel(
                           name: String,
                           comment: String)

case class StateModel(
                       name: String,
                       comment: String)

object ArtifactModel {
  implicit val artifactModelReads: Reads[ArtifactModel] = (
      (__ \ "_id").readNullable[String] ~
      (__ \ "name").read[String] ~
      (__ \ "createdAt").readNullable[Long] ~
      (__ \ "updatedAt").readNullable[Long] ~
      (__ \ "attributes").read[List[AttributeModel]] ~
      (__ \ "stateModels").read[List[StateModel]]
    )(ArtifactModel) // here is the error: "Application does not take parameters"


  implicit val attributeModelReads: Reads[AttributeModel] = (
      (__ \ "name").read[String] ~
      (__ \ "comment").read[String]
    )(AttributeModel)

  implicit val stateModelReads: Reads[StateModel] = (
      (__ \ "name").read[String] ~
      (__ \ "comment").read[String]
    )(StateModel)
}
你能帮帮我吗?在Scala / Play中进行JSON验证的任何解决方案或建议都表示赞赏。

1 个答案:

答案 0 :(得分:8)

Reads对象的类型与apply方法的类型不同。例如,readNullable[String]结果Option[String],而非StringBSONObjectIdDate也是如此。这可以编译,但您可能需要使用一些地图:

  implicit val artifactModelReads: Reads[ArtifactModel] = (
(__ \ "_id").read[BSONObjectID] ~
  (__ \ "name").read[String] ~
  (__ \ "createdAt").read[Date] ~
  (__ \ "updatedAt").read[Date] ~
  (__ \ "attributes").read[List[AttributeModel]] ~
  (__ \ "stateModels").read[List[StateModel]]
)(ArtifactModel.apply _)

你可以在阅读之后,像这样(CONVERT_TO_DATE是虚构的):

  implicit val artifactModelReads: Reads[ArtifactModel] = (
(__ \ "_id").read[BSONObjectID] ~
  (__ \ "name").read[String] ~
  (__ \ "createdAt").read[String].map( s=>CONVERT_TO_DATE(s) ) ~
  (__ \ "updatedAt").read[Date] ~
  (__ \ "attributes").read[List[AttributeModel]] ~
  (__ \ "stateModels").read[List[StateModel]]
)(ArtifactModel.apply _)