Skip to content

Instantly share code, notes, and snippets.

@ayush
Created April 20, 2012 11:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayush/2428013 to your computer and use it in GitHub Desktop.
Save ayush/2428013 to your computer and use it in GitHub Desktop.
Play 2.0 Json <-> Object Binding/Marshalling/Unmarshalling
// 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