Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 如何在编组期间将org.bson.types.ObjectId转换为字符串?_Mongodb_Scala_Casbah_Spray Json - Fatal编程技术网

Mongodb 如何在编组期间将org.bson.types.ObjectId转换为字符串?

Mongodb 如何在编组期间将org.bson.types.ObjectId转换为字符串?,mongodb,scala,casbah,spray-json,Mongodb,Scala,Casbah,Spray Json,看起来我必须编写一个序列化程序/反序列化程序来解决这个问题,但不确定如何解决。我看到了几个使用liftweb框架的示例,但并非没有它。关于如何让它工作有什么帮助吗 注册模型 package model import spray.json._ import spray.json.DefaultJsonProtocol._ import spray.httpx.SprayJsonSupport import com.mongodb.casbah.Imports._ import org.bson.

看起来我必须编写一个序列化程序/反序列化程序来解决这个问题,但不确定如何解决。我看到了几个使用liftweb框架的示例,但并非没有它。关于如何让它工作有什么帮助吗

注册模型

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"))
    )
  }
}
来自RegistrationRoutes类的代码片段

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))
        }          
      }
    }
  }
}
处理complete(result)语句时出现以下错误

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]

我无法测试这一点,但我认为问题在于
fromBson
方法中的以下行(尽管我无法从您的代码中看到如何调用此方法):

将此更改为

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

序列化错误应该消失。

是的,请尝试按如下方式进行字符串:

toString()将返回ObjectId()的字符串表示形式。此字符串值的格式为ObjectId(…)

范例 以下示例对ObjectId()调用toString()方法:

ObjectId(“507c7f79bcf86cd7994f6c0e”).toString()

参考:

如果您能说明调用toString()的结果,这将非常有用。
id = Some(o.as[ObjectId]("_id").toString)