Created
February 28, 2011 13:37
-
-
Save debasishg/847319 to your computer and use it in GitHub Desktop.
This file contains 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
// the enumeration | |
object WeekDay extends Enumeration { | |
type WeekDay = Value | |
val Mon = Value("Monday") | |
val Tue = Value("Tuesday") | |
val Wed = Value("Wednesday") | |
val Thu = Value("Thursday") | |
val Fri = Value("Friday") | |
val Sat = Value("Saturday") | |
val Sun = Value("Sunday") | |
} | |
// the case class containing an enum | |
case class JobStart(name: String, start: WeekDay.Value) | |
// sjson serialization protocol | |
// instance of the typeclass | |
object JobStartProtocol extends DefaultProtocol { | |
import dispatch.json._ | |
import JsonSerialization._ | |
implicit object JobStartFormat extends Format[JobStart] { | |
def reads(json: JsValue): JobStart = json match { | |
case JsObject(m) => | |
JobStart(fromjson[String](m(JsString("name"))), | |
WeekDay.withName(fromjson[String](m(JsString("start"))))) | |
case _ => throw new RuntimeException("JsObject expected") | |
} | |
def writes(p: JobStart): JsValue = | |
JsObject(List( | |
(tojson("name").asInstanceOf[JsString], tojson(p.name)), | |
(tojson("start").asInstanceOf[JsString], tojson(p.start.toString)))) | |
} | |
} | |
// scalatest test case | |
describe("Serialization of enumerated values") { | |
it("should serialize") { | |
import JobStartProtocol._ | |
val js = JobStart("Debasish", WeekDay.Mon) | |
fromjson[JobStart](tojson(js)) should equal(js) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment