首页 > 解决方案 > scala play 读取 json 有条件地填充案例类

问题描述

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

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

标签: jsonscalaplay-json

解决方案


您可以使用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 _)

推荐阅读