Skip to content

Instantly share code, notes, and snippets.

@andypetrella
Created February 19, 2012 21:16
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 andypetrella/1865840 to your computer and use it in GitHub Desktop.
Save andypetrella/1865840 to your computer and use it in GitHub Desktop.
Play Json
class DSO(val prop:String) {}
object DSO {
implicit object DSOFormat extends Format[DSO] {
def reads(json: JsValue): DSO = new DSO(
(json \ "prop").asOpt[String].getOrElse("Not Defined")
)
def writes(d: DSO): JsValue =
JsObject(List(
"prop" -> JsString(d.prop)
))
}
}
trait Format[T] extends Writes[T] with Reads[T]
/**
* Default Json formatters.
*/
object Format extends DefaultFormat
def parse(input: String): JsValue = JerksonJson.parse[JsValue](input)
def stringify(json: JsValue): String = JerksonJson.generate(json)
// and
def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o)
def fromJson[T](json: JsValue)(implicit fjs: Reads[T]): T = fjs.reads(json)
trait Reads[T] {
/**
* Convert the JsValue into a T
*/
def reads(json: JsValue): T
}
scala> val d = new DSO("a prop")
d: DSO = DSO@184a5d6
scala> d.prop
res1: String = a prop
scala> toJson(d)
res2: play.api.libs.json.JsValue = {"prop":"a prop"}
scala> fromJson[DSO](res2).prop
res3: String = a prop</pre>
trait Writes[T] {
/**
* Convert the object into a JsValue
*/
def writes(o: T): JsValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment