mardi 21 avril 2015

How to properly validate JSON in Scala?

import scala.io.Source
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.util.{ Try, Success, Failure }

case class Project(name: String, description: String)

def getScalaProjects: Seq[JsValue] = {

  val url = "http://ift.tt/1Ooj8Ow"
  val gitScalaRepos = Try(Source.fromURL(url).getLines) recover {
    case e: FileNotFoundException =>
      throw new AppException(s"Requested page does not exist: ${e.getMessage}.")
    case e: MalformedURLException =>
      throw new AppException(s"Please make sure to enter a valid URL: ${e.getMessage}.")
    case _ => throw new AppException("An unexpected error has occurred.")
  }

  val gitJSON = Try(Json.parse(gitScalaRepos.get mkString "\n")) match {
    case Success(json) => json
    case Failure(f) => throw new AppException("Could not parse JSON.")
  }

  implicit val projectReads: Reads[Project] = (
    (JsPath \ "name").read[String] and
    (JsPath \ "description").read[String]
  )(Project.apply _)

  for {
    i <- 0 until 5
    p = (gitJSON \ "items")(i).validate[Project]
    p match {
      case s: JsSuccess[Project] => s.get
      case e: JsError => throw new AppException("Could not parse JSON: " +
          JsError.toFlatJson(e).toString())
    }
  } yield p

}

This does not compile (particularily the p match in the for-expression). Please help me to correctly validate the JSON that has been downloaded from the above url and to handle the case when say we change the items to items2 so that it will return a JsError that I need to handle.

Aucun commentaire:

Enregistrer un commentaire