【发布时间】:2024-05-02 13:45:02
【问题描述】:
Play 2.1 (Json.format[...]) 中的实验性“Inception”功能仅适用于案例类(请参阅here)。如何为特征编写隐含的自定义格式。我有以下构造:
sealed trait Plan {
def id: String
def name: String
def apps: Int
def users: Int
def testruns: Int
def price: Int
def prio: Int
}
以及以下扩展特征计划的案例类。
case class Start(
id: String = "start",
name: String = "Start",
apps: Int = 1,
users: Int = 1,
testruns: Int = 10,
price: Int = 99,
prio: Int = 30) extends Plan
case class Pro(
id: String = "pro",
name: String = "Pro",
apps: Int = 2,
users: Int = 5,
testruns: Int = 25,
price: Int = 299,
prio: Int = 20) extends Plan
case class Premium(
id: String = "premium",
name: String = "Premium",
apps: Int = -1,
users: Int = -1,
testruns: Int = -1,
price: Int = 799,
prio: Int = 10) extends Plan
现在我需要在 Plan 伴随对象中编写我的自定义隐式格式 val。我试过了:
object Plan {
implicit val planFormats = (
(__ \ "id").format[String] and
(__ \ "name").format[String] and
(__ \ "apps").format[Int] and
(__ \ "users").format[Int] and
(__ \ "testruns").format[Int] and
(__ \ "price").format[Int] and
(__ \ "prio").format[Int]
)(Plan.apply, unlift(Plan.unapply))
}
但是,特征没有 apply 或 unapply 方法。在 Play 2.1 中为 json 序列化提供隐式 val 的正确方法是什么?
【问题讨论】:
标签: json scala playframework-2.0