Created
December 19, 2011 00:20
-
-
Save wsargent/1494914 to your computer and use it in GitHub Desktop.
Modified JsonSpec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package play.api.json | |
import org.specs2.mutable._ | |
import play.api.json._ | |
object JsonSpec extends Specification { | |
case class User(id: Long, name: String, friends: List[User], skills: Map[String, Int]) | |
implicit object UserFormat extends Format[User] { | |
def reads(json: JsValue): User = User( | |
(json \ "id").as[Long], | |
(json \ "name").as[String], | |
(json \ "friends").asOpt[List[User]].getOrElse(List()), | |
(json \ "skills").asOpt[Map[String, Int]]) | |
def writes(u: User): JsValue = JsObject( | |
Map( | |
"id" -> JsNumber(u.id), | |
"name" -> JsString(u.name), | |
"friends" -> JsArray(u.friends.map(fr => JsObject(Map("id" -> JsNumber(fr.id), "name" -> JsString(fr.name))))), | |
"skills" -> JsArray(u.skills.map { case (k, v) => JsObject(Map(k -> JsNumber(v))) }.toList))) | |
} | |
"JSON" should { | |
"serialize and deserialize" in { | |
val luigi = User(1, "Luigi", List(), Map()) | |
val kinopio = User(2, "Kinopio", List(), Map()) | |
val yoshi = User(3, "Yoshi", List(), Map()) | |
val mario = User(0, "Mario", List(luigi, kinopio, yoshi), Map("scala" -> 10)) | |
val jsonMario = toJson(mario) | |
jsonMario.as[User] must equalTo(mario) | |
(jsonMario \\ "name") must equalTo(Seq(JsString("Mario"), JsString("Luigi"), JsString("Kinopio"), JsString("Yoshi"))) | |
(jsonMario \\ "skills") must equalTo(Map("scala" -> JsNumber(10))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment