简体   繁体   English

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

[英]scala play Read json conditionally populate case class

I have a json that I'm reading using play json api with Read.我有一个 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)

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.我想在联系人中添加最后一个属性重新运行,以便当 json 文件中确实存在“runId”时,它将设置为 true。 How is this possible?这怎么可能?

You can use readNullable and map :您可以使用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 _)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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