Skip to content

Instantly share code, notes, and snippets.

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(
"id" -> JsNumber(,
"name" -> JsString(,
"friends" -> JsArray( => JsObject(Map("id" -> JsNumber(, "name" -> JsString(,
"skills" -> JsArray( { 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)[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.