Created
April 8, 2011 10:25
-
-
Save debasishg/909609 to your computer and use it in GitHub Desktop.
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
// problem with making it really optional in the general case .. | |
// what will be the output for the following ? | |
val str: Option[String] = None | |
tojson(str) // what ? | |
// hence .. | |
val str = None | |
fromjson[Option[String]](tojson[Option[String]](str)) should equal(str) | |
// really optional can be made using specific typeclass instance as follows | |
case class P(lastName: String, firstName: String, age: Option[Int] = None) | |
object PProtocol extends DefaultProtocol { | |
import dispatch.json._ | |
import JsonSerialization._ | |
implicit object PFormat extends Format[P] { | |
def reads(json: JsValue): P = json match { | |
case JsObject(m) => | |
P( | |
fromjson[String](m(JsString("lastName"))), | |
fromjson[String](m(JsString("firstName"))), | |
m.get(JsString("age")).map(fromjson[Option[Int]](_)).getOrElse(None)) | |
case _ => throw new RuntimeException("JsObject expected") | |
} | |
def writes(p: P): JsValue = | |
p.age.map(a => | |
JsObject(List( | |
(tojson("lastName").asInstanceOf[JsString], tojson(p.lastName)), | |
(tojson("firstName").asInstanceOf[JsString], tojson(p.firstName)), | |
(tojson("age").asInstanceOf[JsString], tojson(a))))) | |
.getOrElse( | |
JsObject(List( | |
(tojson("lastName").asInstanceOf[JsString], tojson(p.lastName)), | |
(tojson("firstName").asInstanceOf[JsString], tojson(p.firstName))))) | |
} | |
} | |
// now None is really optional for class P serialization | |
import PProtocol._ | |
val p = P("ghosh", "debasish") | |
println(tojson[P](p)) // prints {"lastName" : "ghosh", "firstName" : "debasish"} | |
println(fromjson[P](tojson[P](p))) // prints P(ghosh,debasish,None) | |
fromjson[P](tojson[P](p)) should equal(p) |
silly me :-( .. Not sure why I thought the companion object will be an error .. Thanks .. will change ..
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please look at my test case (trial-sjson): https://github.com/weiglewilczek/trial-json/blob/master/src/test/scala/SjsonSpec.scala
You won't find any errors there ;-)
To be more general: You can have companion objects for for case classes.