【问题标题】:I could not find what is mistake in following code?我在以下代码中找不到什么错误?
【发布时间】:2017-10-13 07:56:45
【问题描述】:

场景: 我有以下案例类:

case class Student(firstName:String, lastName: String)

我需要为学生写读和写。我提供的 json 是学生序列。 例如:

{
  "College": "Abc",
  "student" : [{"firstName" : "Jack", "lastName":"Starc"}, 
               {"firstName" : "Nicolas", "lastName":"Pooran"}
             ]
}

我的读写操作如下:

implicit val studentFormat = Json.format[Student]
implicit val studentRead = Json.reads[Student]
implicit val  studentWrite = Json.writes[Student]
implicit val studentReadSeq = Reads.seq(studentRead)
implicit val studentWriteSeq = Writes.seq(studentWrite)

现在我必须制作一个类型解析器并检查学生是数组还是简单对象。这里的关键,即学生可以是学生或学生信息。所以我必须根据json中提供的值来做一个解析器。

为此,我做了以下工作:

def studentCheck(jsonValue:  JsObject) = {
  var modifiedJson = Json.obj()
  for ((key, value) <- jsonValue.value) {
    if(value.validate[Student].isSuccess ) {
      val json = 
        studentFormat.writes(value.validate[Student].get).as[JsObject] 
      modifiedJson.+(key, json)
    }
    else if(studentReadSeq.reads(value).isSuccess) {
      //My Code will be here
      modifiedJson
    }
    else {
      println("Error")
      modifiedJson.+(key,value)
    }
  }
}

val studentJson = Json.obj(
  "college" -> "ABC",
  "student" -> Json.arr(
    Json.obj("firstName" -> "Jack", "lastName" -> "Starc"),
    Json.obj("firstName" -> "Nicolas", "entity" -> "Pooran")
  )
)

studentCheck(studentJson)

我在这里遇到的问题是,即使在第一种情况下提供了学生列表,即执行 if 语句而不是 elseif。我怎样才能验证它是否满足所有条件,即如果执行了语句,是否提供了学生对象,如果提供了学生列表,则执行了 elseif 语句。

【问题讨论】:

    标签: json scala playframework-2.3


    【解决方案1】:

    您有一种更好、更安全、更实用的方法来验证 json。

    假设您有一个College 案例类:

    case class College(college: String, students: List[Student])

    你可以有这样的阅读器:

    object College{
       implicit val collegeReads = Reads[College] = (
         (JsPath \ "college").read[String] and
         (JsPath \ "students").read[List[Student]
       ) (College.apply _)
    }
    

    然后为了验证它,你可以这样做:

    def foo(jsonValue:  JsObject)={
       jsonValue.validate[College].fold(
          errors =>  ,//handle parsing errors
          collage => //your code when the parsing is successfull.
       )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多