Last active
December 30, 2016 05:55
-
-
Save blancosj/c3a23bbbdcdbbcf54a793d880f6576a4 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
object EnumFormat { | |
implicit def jsonReads[A](enum: Enumeration): Reads[A] = new Reads[A] { | |
def reads(json: JsValue): JsResult[A] = json match { | |
case JsString(s) => { | |
try { | |
JsSuccess(enum.withName(s).asInstanceOf[A]) | |
} catch { | |
case _: NoSuchElementException => | |
JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'") | |
} | |
} | |
case _ => JsError("String value expected") | |
} | |
} | |
implicit def jsonWrites[A]: Writes[A] = new Writes[A] { | |
def writes(v: A): JsValue = JsString(v.toString) | |
} | |
implicit def jsonFormat[A](enum: Enumeration): Format[A] = { | |
Format(jsonReads(enum), jsonWrites) | |
} | |
} | |
object DeviceStatus extends Enumeration { | |
val UNKNOWN = DeviceStatusType(0x0) | |
val REGISTERED = DeviceStatusType(0x1) | |
val NO_REGISTERED = DeviceStatusType(0x1000) | |
case class DeviceStatusType(code: Int) extends Val(code) { | |
import play.api.libs.json._ | |
import play.api.libs.functional.syntax._ | |
implicit def valueTo(v: Value): DeviceStatusType = v.asInstanceOf[DeviceStatusType] | |
} | |
implicit val jsonFormat: Format[DeviceStatus.DeviceStatusType] = EnumFormat.jsonFormat(DeviceStatus) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment