Last active
August 29, 2015 14:08
-
-
Save atamborrino/1d992ebb942cd5518ca2 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
// Enum type based on Sum types (OR) | |
trait ADTEnum[A] { | |
import play.api.data.mapping.json.Writes._ | |
import play.api.data.mapping.json.Rules._ | |
val list: Seq[A] | |
def withName(name: String): Option[A] = { | |
list.find(_.toString.toLowerCase == name.toLowerCase) | |
} | |
implicit val jsonReads: Rule[JsValue, A] = Rule.fromMapping { | |
case JsString(str) => | |
withName(str) match { | |
case Some(name) => Success(name) | |
case None => Failure(Seq(ValidationError(s"error.unknownADTEnum"))) | |
} | |
case _ => Failure(Seq(ValidationError(s"error.ADTEnumMustBeAString"))) | |
} | |
implicit val jsonWrites: Write[A, JsString] = Write(a => JsString(a.toString)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cool thanks, here is an implementation with Spray and Play Json marshalling (dependencies: play-json, spray-json) => https://gist.github.com/cyppan/edcda7e67c1551e0122c