2

我有一个用 enumeratum 创建的枚举

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)
4

1 回答 1

3

仅当您的键是 a时才会隐式提供a的播放Format转换器,因为 JSON 对象键必须是字符串。它没有意识到最终是a (或者,更确切地说,是 a )。因此,您需要手动编写自己的和转换器,或者映射到您在上面所做的那样的键。对于它的价值,第一个解决方案将大致采用以下结构:MapMapStringLanguageStringJsStringReadsWritesMap[Language, String]LanguageStringvalues: 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)
于 2018-09-20T14:59:42.833 回答