如何在Scala枚举中编写Reads [T]和Writes [T](播放框架2.1) [英] How to write Reads[T] and Writes[T] in scala Enumeration (play framework 2.1)
问题描述
我对Play Framework 2.1中的新ScalaJson功能迷失了一些. 我想在枚举中写读和写.
I'm a little bit lost with the new ScalaJson Feature in Play Framework 2.1. I would like to write Reads and Writes in my Enumeration.
这是我的代码:
object EnumA extends Enumeration {
type EnumA = Value
val VAL1, VAL2, VAL3 = Value
def parse(str:String) : EnumA = {
str.toUpperCase() match {
case "VAL1" => VAL1
case "VAL2" => VAL2
case "VAL3" => VAL3
case _ => null
}
}}
有什么主意吗?
谢谢.
推荐答案
简短答案:使用类似 Play Enumeration Utils 的方法
Short answer: use something like Play Enumeration Utils.
长答案,而不是将枚举放入您的枚举,您可以为枚举类型创建可重复使用的枚举:
Long answer, instead of putting a Reads in your enum, you can create a re-useable Reads for Enumeration types:
object EnumA extends Enumeration {
type EnumA = Value
val VAL1, VAL2, VAL3 = Value
}
object EnumUtils {
def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
def reads(json: JsValue): JsResult[E#Value] = json match {
case JsString(s) => {
try {
JsSuccess(enum.withName(s))
} catch {
case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
}
}
case _ => JsError("String value expected")
}
}
}
然后,当您想将某些内容解析为枚举时,请为范围内的特定Enum类型创建一个隐式的Reads:
Then when you want to parse something to an enum, create an implicit Reads for your specific Enum type in scope:
import some.thing.EnumUtils
implicit val myEnumReads: Reads[EnumA.Value] = EnumUtils.enumReads(EnumA)
val myValue: EnumA.Value = someJsonObject.as[EnumA.Value]
或
val myValue: EnumA.Value = someJsonObject.asOpt[EnumA.Value].getOrElse(sys.error("Oh noes! Invalid value!"))
(在Scala中使用null被认为是错误的形式.)
(It's considered bad form to use null in Scala.)
将枚举写为JsValues更简单:
Writing enums as JsValues is simpler:
object EnumUtils {
...
implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
def writes(v: E#Value): JsValue = JsString(v.toString)
}
}
然后只需在尝试编写枚举(或将其显式传递给toJson
函数:
Then just import that into scope before you attempt to write an enum (or pass it explicitly to the toJson
function:
import EnumUtils.enumWrites
val myEnumJson: JsValue = Json.toJson(EnumA.VAL1)
您可以类似地使函数结合读取和写入来创建Format对象:
You can similarly make a function to create a Format object combining both Reads and Writes:
object EnumUtils {
....
implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
Format(EnumReader.enumReads(enum), EnumWriter.enumWrites)
}
}
这篇关于如何在Scala枚举中编写Reads [T]和Writes [T](播放框架2.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!