简体   繁体   中英

Serialize to object using scala mongo driver?

I'm new to the scala mongo driver and am trying to understand how to map a class from a Document? None of the documentation seems to show how this is done. In the .net driver, its as easy as passing a generic and having fields auto mapped. Is there nothing similar in scala?

They don't make it easy. Digging through the java, I came up with this solution:

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")
}

Example for serializing and deserializing object using mongo macro handler.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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