scala play Read json有条件地填充案例类

scala play Read json有条件地填充案例类,json,scala,play-json,Json,Scala,Play Json,我有一个json,我正在使用play json api读取 { "runId" : "123", "name" : "ABC", "location" : "DEF" } implicit val jsonRead: Reads[Contact] = ( (JsPath \ "runId").readWithDefault(generateRunId) and (JsPath \ "name").read[String] and

我有一个json,我正在使用play 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)

我想在联系人中添加最后一个属性重新运行,以便在json文件中确实存在“runId”时,将其设置为true。这怎么可能呢?

您可以使用
readNullable
map

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