To write the enum as a string as cchantep says you can use Writes.enumNameWrites, we specifically use to read and write the ID. Therefore we have an EnumFormat in the package global for enums:
package object enums {
implicit def reads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
def reads(json: JsValue): JsResult[E#Value] = json match {
case JsNumber(s) =>
try {
JsSuccess(enum.apply(s.toInt))
} catch {
case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
}
case _ => JsError("Number value expected")
}
}
implicit def writes[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
def writes(v: E#Value): JsValue = JsNumber(v.id)
}
implicit def formatID[E <: Enumeration](enum: E): Format[E#Value] =
Format(reads(enum), writes)
def readsString[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")
}
}
implicit def writesString[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
def writes(v: E#Value): JsValue = JsString(v.toString)
}
implicit def formatString[E <: Enumeration](enum: E): Format[E#Value] =
Format(readsString(enum), writesString)
}
And used:
object SearchRequest extends Enumeration(1) {
type SearchRequest = Value
val ONE /*1*/ , TWO /*2*/ , ETC /*n*/ = Value
implicit val searchRequestFormat: Format[SearchRequest] = formatID(SearchRequest)
}
Writes.enumNameWrites
is provided. W/o the case class definition, I find weird to havescala.Enumeration.Value
as property type, rather thanE#Value
(for someE <: scala.Enumeration
) – cchantepSearchRequest
and is it not used by other libraries? – pmescala.Enumeration
entirely? – pme