[英]scala play Read json conditionally populate case class
我有一个 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)
我想在联系人中添加最后一个属性重新运行,以便当 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 _)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.