Domanda

there is a simple model class that contains some database ids. It looks like this:

case class Post(id: ObjectId, owner: Option[ObjectId], title: String)

object Post {
  implicit val implicitPostWrites = Json.writes[Post]
}

With this code, the compiler gives me the following error:

No implicit Writes for com.mongodb.casbah.commons.TypeImports.ObjectId available. implicit val implicitFooWrites = Json.writes[Foo]

It is obvious what's missing, but I don't know how to provide an implicit Writes for com.mongodb.casbah.commons.TypeImports.ObjectId. How can this be done?

È stato utile?

Soluzione

The error means that it doesn't know how to serialize ObjectId and expects you to provide a Writer for it. This is one way to serialize it:

object Post {

  implicit val objectIdWrites = new Writes[ObjectId] {
      def writes(oId: ObjectId): JsValue = {
        JsString(oId.toString)
      }
  }

   implicit val implicitPostWrites = Json.writes[Post]
}

More information and explanations are available here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top