简体   繁体   English

如何在Akka-http中编组和解组mongo ObjectId

[英]How to marshall and unmarshall mongo ObjectId in akka-http

How do i convert mongo ObjectId to string id and vice versa in akka-http for JSON response For this User class 如何在Akka-http中将mongo ObjectId转换为字符串ID,反之亦然,以获取JSON响应对于此User类

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

this jsonFormat4 doesn't work. 这个jsonFormat4不起作用。

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) 错误:(21,40)找不到类型JsonSupport.this.JF [org.mongodb.scala.bson.ObjectId]的证据参数的隐式值隐式val userFormat = jsonFormat4(User.apply)

You need to put in scope a custom serializer for the ObjectId type: 您需要为ObjectId类型放入自定义序列化程序的作用域:

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. 然后将此对象导入您的路由范围,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM