Skip to content

Instantly share code, notes, and snippets.

@maizy
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maizy/4b60392ad69c56747dd1 to your computer and use it in GitHub Desktop.
Save maizy/4b60392ad69c56747dd1 to your computer and use it in GitHub Desktop.
play framework scala: json readers example
// for `play console`
// enter to paste mode before by running `:paste`
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class Account(name: String)
case class Repo(
name: String,
owner: Account,
description: Option[String] = None)
val objJson = """{"name": "one", "d": "some description"}"""
val objJson2 = """{"name": "two"}"""
val objs = s"""[$objJson, $objJson2]"""
val parsed1: JsValue = Json.parse(objJson)
val parsed2: JsValue = Json.parse(objJson2)
//reader for object
val reader: Reads[Repo] =
(
(__ \ "name").read[String] and
(__ \ "d").readNullable[String] //Optional field (None for 'null' or key not exists)
) apply((name, d) => Repo(name, Account("user_acc"), d))
//construct reader for list of objects
val listReader = Reads.seq[Repo](reader)
val resBuffer = scala.collection.mutable.ListBuffer[Repo]()
val tuples1 = reader.reads(parsed1)
tuples1 foreach {
resBuffer.append(_)
}
val tuples2 = reader.reads(parsed2)
tuples2 foreach {
resBuffer.append(_)
}
val parsedObjs: JsValue = Json.parse(objs)
val readObjs = listReader.reads(parsedObjs)
readObjs foreach {
resBuffer ++= _
}
resBuffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment