【问题标题】:Serialize to object using scala mongo driver?使用 scala mongo 驱动程序序列化为对象?
【发布时间】:2021-04-28 15:53:34
【问题描述】:

我是 scala mongo 驱动程序的新手,我想了解如何从 Document 映射一个类?似乎没有任何文档显示这是如何完成的。在 .net 驱动程序中,它就像传递泛型并自动映射字段一样简单。 scala中没有类似的东西吗?

【问题讨论】:

    标签: mongodb scala


    【解决方案1】:

    他们并不容易。通过java挖掘,我想出了这个解决方案:

    import org.bson.codecs.DecoderContext
    import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
    import org.bson.codecs.configuration.CodecRegistry
    import org.bson.{BsonDocumentReader, BsonDocumentWrapper}
    import org.mongodb.scala.bson.codecs.{DEFAULT_CODEC_REGISTRY, Macros}
    import org.mongodb.scala.bson.collection.mutable.Document
    
    import scala.reflect.classTag
    
    case class Person(firstName: String, lastName: String)
    
    object MongoTest extends App {
    
      val personCodecProvider = Macros.createCodecProvider[Person]()
      val codecRegistry: CodecRegistry = fromRegistries(fromProviders(personCodecProvider), DEFAULT_CODEC_REGISTRY)
    
      val document = Document("firstName" -> "first", "lastName" -> "last")
      val bsonDocument = BsonDocumentWrapper.asBsonDocument(document, DEFAULT_CODEC_REGISTRY)
    
      val bsonReader = new BsonDocumentReader(bsonDocument)
      val decoderContext = DecoderContext.builder.build
      val codec = codecRegistry.get(classTag[Person].runtimeClass)
      val person: Person = codec.decode(bsonReader, decoderContext).asInstanceOf[Person]
    
      println(s"person: $person")
    }
    

    【讨论】:

    • org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY 已弃用,请使用 import MongoClient.DEFAULT_CODEC_REGISTRY。伟大的帖子格雷德!
    【解决方案2】:

    使用 mongo 宏处理程序序列化和反序列化对象的示例。

    import reactivemongo.api.bson.{BSON, BSONDocument, Macros}
    
    case class Person(name:String = "SomeName", age:Int = 20)
    
    implicit val personHandler = Macros.handler[Person]
    
    //Serialize
    val bsonPerson = BSON.writeDocument[Person](Person())
    
    println(s"${BSONDocument.pretty(bsonPerson.getOrElse(BSONDocument.empty))}")
    
    //Deserialize
    
    val bsonDocumentPerson = BSONDocument("name"-> "MyNameHere", "age"->35)
    
    val scalaObjPerson: Person = BSON.read[Person](bsonDocumentPerson).getOrElse(Person())
    
    printf(s"Scala person obj = $scalaObjPerson")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多