mongodbscalacasbahspray-json

How to convert org.bson.types.ObjectId to String during marshalling?


Looks like I have to write a serializer/deserializer to fix this, but not exactly sure how. I see several examples using liftweb framework, but not without it. Any help on how to get this working?

Registration Model

package model

import spray.json._
import spray.json.DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport
import com.mongodb.casbah.Imports._
import org.bson.types.ObjectId
import com.mongodb.DBObject
import com.mongodb.casbah.commons.{MongoDBList, MongoDBObject}

case class Registration(
  system: String, 
  identity: String, 
  id: Option[String] = None)

object RegistrationJsonProtocol extends DefaultJsonProtocol {
  implicit val adsRegistrationFormat = jsonFormat3(Registration)
}

object RegistrationMap {
  def toBson(registration: Registration): DBObject = {
    MongoDBObject(
      "system"         -> registration.system,
      "identity"       -> registration.identity,
      "_id"            -> new ObjectId(registration.id.getOrElse(new ObjectId().toString))
    )
  }

  def fromBson(o: DBObject): Registration = {
    Registration(
      system = o.as[String]("system"),
      identity = o.as[String]("identity"),
      id = Some(o.as[String]("_id"))
    )
  }
}

Code snippet from RegistrationsRoutes class

val route: Route = {
  withService("registrations") { service =>

    import model.RegistrationJsonProtocol._

    postRegistration {
      entity(as[Registration]) { registration =>
        val future = (service ? PostRegistrationMessage(registration)).mapTo[Registration]

        onComplete(future) {
          case Success(result) =>
            log.debug(s"result: ${result}")
            complete(result)

          case Failure(e) =>
            log.error(s"Error: ${e.toString}")
            complete(StatusCodes.InternalServerError, Message(ApiMessages.UnknownException))
        }          
      }
    }
  }
}

Getting following error when processing complete(result) statement

13:08:17.538 [microservice-system-akka.actor.default-dispatcher-5] DEBUG akka.actor.ActorSystemImpl - result: Registration(system1,identity1,Some(54bd48110364eb78f7b84ce3))
13:08:17.643 [microservice-system-akka.actor.default-dispatcher-5] ERROR akka.actor.RepointableActorRef - Error during processing of request HttpRequest(POST,http://localhost:8878/api/v1/registrations,List(Accept-Language: en-US, en;q=0.8, es;q=0.6, te;q=0.4, Accept-Encoding: gzip, deflate, DNT: 1, Content-Type: application/json, Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo, User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36, Content-Length: 165, Connection: keep-alive, Host: localhost:8878),HttpEntity(application/json,{"system":"system1", "identity":"identity1"),HTTP/1.1)
java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
    at spray.json.BasicFormats$StringJsonFormat$.write(BasicFormats.scala:119) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.json.PimpedAny.toJson(package.scala:39) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.json.StandardFormats$OptionFormat.write(StandardFormats.scala:34) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.json.StandardFormats$OptionFormat.write(StandardFormats.scala:32) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:36) ~[spray-json_2.10-1.2.6.jar:na]
    at com.ericsson.admcore.model.ADSRegistrationJsonProtocol$.productElement2Field(ADSRegistration.scala:20) ~[classes/:na]
    at spray.json.ProductFormatsInstances$$anon$6.write(ProductFormatsInstances.scala:155) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.json.ProductFormatsInstances$$anon$6.write(ProductFormatsInstances.scala:146) ~[spray-json_2.10-1.2.6.jar:na]
    at spray.httpx.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:43) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:42) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.Marshaller$MarshallerDelegation$$anonfun$apply$1.apply(Marshaller.scala:58) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.Marshaller$MarshallerDelegation$$anonfun$apply$1.apply(Marshaller.scala:58) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.Marshaller$MarshallerDelegation$$anonfun$apply$2.apply(Marshaller.scala:61) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.Marshaller$MarshallerDelegation$$anonfun$apply$2.apply(Marshaller.scala:60) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.Marshaller$$anon$2.apply(Marshaller.scala:47) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.BasicToResponseMarshallers$$anon$1.apply(BasicToResponseMarshallers.scala:35) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.BasicToResponseMarshallers$$anon$1.apply(BasicToResponseMarshallers.scala:22) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshaller$$anonfun$compose$1.apply(Marshaller.scala:69) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshaller$$anonfun$compose$1.apply(Marshaller.scala:69) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshaller$$anon$3.apply(Marshaller.scala:81) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshallable$$anon$6.marshal(Marshaller.scala:141) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshallable$$anon$7.apply(Marshaller.scala:145) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.httpx.marshalling.ToResponseMarshallable$$anon$7.apply(Marshaller.scala:144) ~[spray-httpx_2.10-1.3.1.jar:na]
    at spray.routing.RequestContext.complete(RequestContext.scala:237) ~[spray-routing_2.10-1.3.1.jar:na]
    at spray.routing.directives.RouteDirectives$$anonfun$complete$1$$anon$3.apply(RouteDirectives.scala:49) ~[spray-routing_2.10-1.3.1.jar:na]
    at spray.routing.directives.RouteDirectives$$anonfun$complete$1$$anon$3.apply(RouteDirectives.scala:48) ~[spray-routing_2.10-1.3.1.jar:na]
    at spray.routing.directives.OnCompleteFutureMagnet$$anon$1$$anonfun$happly$1$$anonfun$apply$1.apply(FutureDirectives.scala:63) ~[spray-routing_2.10-1.3.1.jar:na]
    at spray.routing.directives.OnCompleteFutureMagnet$$anon$1$$anonfun$happly$1$$anonfun$apply$1.apply(FutureDirectives.scala:62) ~[spray-routing_2.10-1.3.1.jar:na]
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) ~[scala-library.jar:na]
    at scala.concurrent.impl.ExecutionContextImpl$$anon$3.exec(ExecutionContextImpl.scala:107) ~[scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library.jar:na]

Solution

  • I couldn't test this, but I think the issue lies within the following line in the fromBson method (although I can't see from your code how this method is called):

    id = Some(o.as[String]("_id"))
    

    Change this to

    id = Some(o.as[ObjectId]("_id").toString)
    

    and the serialization error should be gone.