Last active
August 29, 2015 14:04
-
-
Save maizy/4b60392ad69c56747dd1 to your computer and use it in GitHub Desktop.
play framework scala: json readers example
This file contains hidden or 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
// 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