我有一个包含两个案例类的 scala 文件。ContactInfo 是 Profile 的一部分。如果我将 ContactInfo 案例类放在 Profile 案例类之后,则会引发两个编译异常。为什么课程的顺序很重要?如果我在 Profile 之前移动 ContactInfo,错误就消失了。
[error] No Json deserializer found for type Option[models.ContactInfo]. Try to implement an implicit Writes or Format for this type.
[error] "contactInfo" -> p.contactInfo
[error] No Json deserializer found for type models.ContactInfo. Try to implement an implicit Reads or Format for this type.
[error] (__ \ 'contactInfo).readNullable[ContactInfo]
case class Profile(
id: ObjectId = new ObjectId,
contactInfo: Option[ContactInfo] = None
)
object Profile extends ProfileJson
trait ProfileJson {
implicit val profileJsonWrite = new Writes[Profile] {
def writes(p: Profile): JsValue = {
Json.obj(
"id" -> p.id,
"contactInfo" -> p.contactInfo
)
}
}
implicit val profileJsonRead = (
(__ \ 'id).read[ObjectId] ~
(__ \ 'contactInfo).readNullable[ContactInfo]
)(Profile.apply _)
}
case class ContactInfo(
givenName: String
)
object ContactInfo {
implicit val contactInfoJsonWrite = new Writes[ContactInfo] {
def writes(a: ContactInfo): JsValue = {
Json.obj(
"givenName" -> a.givenName
)
}
}
implicit val contactInfoJsonRead = (
(__ \ 'givenName).read[String]
)(ContactInfo.apply _)
}