为没有字段的Java Enum创建读/写

时间:2014-02-12 18:53:03

标签: json scala playframework enums

使用Play Framework JSON库,如何为没有字段的Java枚举创建ReadsWrites

public enum EnumNoFields { RED, WHITE, BLUE }

implicit val EnumNoFieldsReads: Reads[EnumNoFields] = ?
implicit val EnumNoFieldsWrites: Writes[EnumNoFields] = ?

2 个答案:

答案 0 :(得分:6)

我只是使用了Enum#name

  implicit val EnumNoFieldsReads: Reads[EnumNoFields] =
    (JsPath \ "displayValue").read[String].map{x: String => EnumNoFields.valueOf(x)}

  implicit val EnumNoFieldsWrites: Writes[EnumNoFields] =
    (JsPath \ "displayValue").write[String].contramap{x:EnumNoFields => x.name}

答案 1 :(得分:6)

通用解决方案如下所示:

def javaEnumFormat[E <: Enum[E] : ClassTag] = new Format[E] {
  override def reads(json: JsValue): JsResult[E] = json.validate[String] match {
    case JsSuccess(value, _) => try {
      val clazz = implicitly[ClassTag[E]].runtimeClass.asInstanceOf[Class[E]]
      JsSuccess(Enum.valueOf(clazz, value))
    } catch {
      case _: IllegalArgumentException => JsError("enumeration.unknown.value")
    }
    case JsError(_) => JsError("enumeration.expected.string")
  }

  override def writes(o: E): JsValue = JsString(o.toString)
}

你可以这样使用:

implicit val enumNoFieldsFormat = javaEnumFormat[EnumNoFields]