json - 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。这怎么可能?
解决方案
您可以使用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 _)
推荐阅读
- spring-data-neo4j - Spring Data Neo4J - 管理与图形数据库的连接
- python - 如何在 Python 中创建模块?
- google-chrome - 从托管页面将 HTML 签名注入 Gmail
- python-3.x - Tkinter 滚动条没有出现
- javascript - React 表单提交正在触发重新渲染(尽管有 e.preventDefault)
- python-3.x - 运行批处理文件找不到默认 Python
- ruby-on-rails - Rails/GraphQL/Devise:对于运行 GraphQL 的应用程序,有什么好的替代方案吗?
- algorithm - 基于用户输入物质像素处理器的白平衡算法
- angular - 我如何清除另一个组件上的所有验证器,角度 7 反应形式
- alexa-skills-kit - alexa说完后自动调用方法