如何为 Scala Play 编写读取函数

How write Reads function for Scala Play

我对读取有疑问。我有这样的功能:

  private val myFunc: Reads[Foo] =
    (__ \ "foo")
      .readNullable[Foo]
      .map {
        case Some(foo) => foo
        case None =>
          (__ \ "bar").readNullable[Bar].map {
            case Some(bar) => Foo(bar.value)
            case None => Foo("")
          }
      }

但是我遇到这样的编译器问题:

[error]  found   : play.api.libs.json.Reads[com.me.Foo]
[error]  required:com.me.Foo

我该如何解决这个问题?

import play.api.libs.json._

case class Foo(lorem: String)

implicit val fooReads: Reads[Foo] = Json.reads[Foo]

case class Bar(value: String)

implicit val barReads: Reads[Bar] = Json.reads[Bar]

val reads: Reads[Foo] = (__ \ "foo").read[Foo].orElse {
  (__ \ "bar").readNullable[Bar].map {
    case Some(bar) => Foo(bar.value)
    case None => Foo("")
  }
}

// ---

Json.parse("""{"foo":{"lorem":"ipsum"}}""").validate(reads)
// JsSuccess(Foo(ipsum),/foo)

Json.parse("""{"bar":{"value":"ipsum"}}""").validate(reads)
// JsSuccess(Foo(ipsum),/bar)

因为在 orElse 中实例化 Bar 没有任何价值:

val reads: Reads[Foo] = (__ \ "foo").read[Foo].orElse {
  (__ \ "bar" \ "value").readNullable[String].map {
    case Some(bar) => Foo(bar)
    case None => Foo("")
  }
}