Created
April 20, 2012 11:56
-
-
Save ayush/2428013 to your computer and use it in GitHub Desktop.
Play 2.0 Json <-> Object Binding/Marshalling/Unmarshalling
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
// taken from http://www.playframework.org/documentation/api/2.0/scala/play/api/libs/json/package.html | |
case class User(id: Long, name: String, friends: List[User]) | |
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())) | |
def writes(u: User): JsValue = JsObject(List( | |
"id" -> JsNumber(u.id), | |
"name" -> JsString(u.name), | |
"friends" -> JsArray(u.friends.map(fr => JsObject(List("id" -> JsNumber(fr.id), | |
"name" -> JsString(fr.name))))))) | |
} | |
//then in a controller: | |
object MyController extends Controller { | |
def displayUserAsJson(id: String) = Action { | |
Ok(toJson( User(id.toLong, "myName", friends: List()))) | |
} | |
def saveUser(jsonString: String)= Action { | |
val user = play.api.libs.json.parse(jsonString).as[User] | |
myDataStore.save(user) | |
Ok | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment