2017-10-13 13 views
0

시나리오 : 나는 경우 클래스 다음 한 : 나는 쓸 필요가다음 코드에서 실수가 무엇인지 발견 할 수 없습니까?

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

읽기 및 학생을 위해 씁니다. 제가 제공하는 json은 Sequence of Student입니다. 예를 들어 는 :

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) 

가 지금은 형식 파서을하고 학생이 배열 또는 단순한 객체인지 여부를 확인해야 :

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

내 읽기와 같은 기록 작성했습니다. 여기서 핵심은 학생 또는 학생 정보 일 수 있습니다. 그래서 저는 json에서 제공되는 가치에 기초하여 파서를 만들어야합니다. 이를 위해

가 나는 다음과 같은했을 : 문이 대신 ELSEIF의 실행되면

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) 

내가 여기 얻을 문제, 심지어 학생들의 목록 첫 번째 경우, 즉를 제공했다. 모든 조건을 만족하도록 유효성을 검사 할 수있는 방법, 즉 진술이 실행되면 학생 개체가 제공되고 학생 목록이 제공되는 경우 elseif 문이 실행됩니다.

답변

0

json의 유효성을 검사하는 데 훨씬 더 안전하고 기능적인 방법이 있습니다.

의 당신이 College 경우 클래스가 있다고 가정하자

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

그 다음을 검증하기 위해, 당신은 할 수 있습니다 :

당신은 이와 같은 독자를 가질 수

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

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