2

2つのケースクラスを含む1つのscalaファイルがあります。ContactInfoはプロファイルの一部です。Profileケースクラスの後にContactInfoケースクラスを配置すると、2つのコンパイル例外がスローされます。なぜクラスの順序が重要なのですか?プロファイルの前に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 _)
}
4

1 に答える 1

0

クラスの順序は問題ではないと思います。それらを暗黙的に見つけるためのルールはあなたの問題だと思います。コンパニオン オブジェクトの順序を変更してみてください。

于 2013-03-15T20:35:18.503 に答える