在映射中使用枚举枚举不起作用



我有一个用枚举创建的枚举:

sealed trait Language extends EnumEntry
object Language
extends Enum[Language]
with PlayInsensitiveJsonEnum[Language] {
val values: IndexedSeq[Language] = findValues
case object DE extends Language
...
}

如果我在地图中使用它,它会抛出:

No instance of play.api.libs.json.Format is available for scala.collection.immutable.Map[finnova.bpf.api.entity.Language, java.lang.String] in the implicit scope (Hint: if declared in the same file, make sure it's declared before)

以下是定义:

case class I18nEntry(values: Map[Language, String])
object I18nEntry {
implicit val jsonFormat: Format[I18nEntry] = Json.format[I18nEntry]
}

这在这里工作:

case class I18nEntry(values: Map[String, String], language: Language)

仅当您的Map键是String时,才会隐式提供Map的 PlayFormat转换器,因为 JSON 对象键必须是字符串。它没有意识到Language最终是一个String(或者更确切地说,是一个JsString(。因此,您需要手动编写自己的ReadsWritesMap[Language, String]转换器,或者将Language映射到String键,例如您上面所做的values: Map[String, String]。对于它的价值,第一个解决方案大致采用以下结构:

val langMapReads: Reads[Map[Language, String]] = ???
val langMapWrites: Writes[Map[Language, String]] = ???
implicit val langMapFormat: Format[Map[Language, String]] = Format(langMapReads, langMapWrites)

最新更新