scala play有条件地填充case类,读取json

问题描述 投票:0回答:1

我有一个正在使用Read的play json api读取的json。

 {
  "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,以便当json文件中确实存在“ runId”时,它将设置为true。这怎么可能?

json scala playback
1个回答
0
投票

您可以使用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 _)
© www.soinside.com 2019 - 2024. All rights reserved.