我有一个正在使用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。这怎么可能?
您可以使用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 _)