我的情况是我有一个传入的数据模型
case class Person(name: String,
age: Int,
contact: Int)
但是,我想忽略 name 属性,因为我不会接收它但是我需要它将它保存在我稍后注入的DB中。
一个选项可能是使其成为可选项,但在这种情况下,我需要为DB创建另一个模型,这是多余的。
任何人都可以使用JSONCombinator READ提供解决方案以避免读取该字段吗?
由于
答案 0 :(得分:3)
创建自定义Reads
并将名称默认为空字符串:
import play.api.libs.json._ // JSON library
import play.api.libs.json.Reads._ // Custom validation helpers
import play.api.libs.functional.syntax._ // Combinator syntax
implicit val customReads: Reads[Person] = (
(JsPath \ "age").read[Int] and
(JsPath \ "contact").read[Int]
)((age, contact) => Person(name = "", age = age, contact = contact))
修改
implicit val customWrites: Writes[Person] = (
(JsPath \ "age").write[Int] and
(JsPath \ "contact").write[Int]
)((person) => (p.age, p.contact))