Created
February 19, 2012 21:16
-
-
Save andypetrella/1865840 to your computer and use it in GitHub Desktop.
Play Json
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
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) | |
)) | |
} | |
} |
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
trait Format[T] extends Writes[T] with Reads[T] | |
/** | |
* Default Json formatters. | |
*/ | |
object Format extends DefaultFormat |
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
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) |
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
trait Reads[T] { | |
/** | |
* Convert the JsValue into a T | |
*/ | |
def reads(json: JsValue): T | |
} |
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
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> |
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
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