Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modified JsonSpec
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
You can’t perform that action at this time.