2
votes

How do i convert mongo ObjectId to string id and vice versa in akka-http for JSON response For this User class

case class User(_id: ObjectId, email: String, name: Option[String], birthDate: Option[String])

this jsonFormat4 doesn't work.

implicit val userFormat = jsonFormat4(User.apply)

This error is thrown.

Error:(21, 40) could not find implicit value for evidence parameter of type JsonSupport.this.JF[org.mongodb.scala.bson.ObjectId] implicit val userFormat = jsonFormat4(User.apply)

1
What have you tried by yourself?cchantep

1 Answers

4
votes

You need to put in scope a custom serializer for the ObjectId type:

object MongoDBProtocol extends DefaultJsonProtocol {

  implicit object ObjectIdSerializer extends RootJsonFormat[ObjectId] {
    override def write(obj: ObjectId): JsValue = {
      JsString(obj.toHexString)
    }

    override def read(json: JsValue): ObjectId = {
      val ob = new ObjectId(json.toString())
      ob
    }
  }
}

Then import this object in your route scope and it should work.