Scala Play的写入读取功能如何

时间:2019-06-04 09:19:21

标签: scala playframework play-json

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

  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

我该如何解决?

1 个答案:

答案 0 :(得分:3)

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)

由于在Bar中实例化orElse没有价值:

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