简体   繁体   中英

scala play Read json conditionally populate case class

I have a json that I'm reading using play json api with Read.

 {
  "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)

I want to add the last attribute rerun in the Contact so that when "runId" does exists in the json file, it would be set to true. How is this possible?

You can use readNullable and 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 _)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM