Play framework + Scala + Json

1052 ワード

case class ErrorCode(status: Int, message: String)

implicit val errorcodeWriters = new Writes[ErrorCode] {
    def writes(errorcode: ErrorCode) = Json.obj (
      "status" -> errorcode.status,
      "message" -> errorcode.message
    )
}

implicit val errorcodeWriters: Writes[ErrorCode] = (
    (JsPath \ "status").write[Int] and
    (JsPath \ "message").write[String]
)(unlift(ErrorCode.unapply))

implicit val errorcodeReaders: Reads[ErrorCode] = (
    (JsPath \ "status").read[Int] and
    (JsPath \ "message").read[String]
)(ErrorCode.apply _)


case class Location(lat: Double, long: Double)

val xjson = Json.toJson(ErrorCode(101, "zxcv"))

val status = (xjson \ "status").as[String]

val errcode:JsResult[ErrorCode] =  xjson.validate[ErrorCode]
errcode match {
    case s: JsSuccess[ErrorCode] => Logger.info(s"deparsed message ${s.get.message}")
    case e: JsError => println("Errors: " + JsError.toFlatForm(e).toString)
}