scala play 读取 json 有条件地填充案例 class

scala play Read json conditionally populate case class

我有一本 json,我正在使用播放 json api 阅读。

 {
  "runId" : "123",
  "name" : "ABC",
  "location" : "DEF"
}

implicit val jsonRead: Reads[Contact] = (
        (JsPath \ "runId").readWithDefault(generateRunId) and
          (JsPath \ "name").read[String] and
          (JsPath \ "location").read[String]
    )(Contact.apply _)

case class Contact(runId : String, name : String, location : String, rerun : Boolean)

我想在 Contact 中添加最后一个属性 rerun 以便当 "runId" 确实存在于 json 文件,它将被设置为 true。这怎么可能?

您可以使用 readNullablemap:

implicit val jsonRead: Reads[Contact] = (
  (JsPath \ "runId").readWithDefault(generateRunId) and
    (JsPath \ "name").read[String] and
    (JsPath \ "location").read[String] and
    (JsPath \ "runId").readNullable[String].map(_.nonEmpty)
)(Contact.apply _)