使用 scala mongo 驱动程序序列化为对象? [英] Serialize to object using scala mongo driver?

查看:43
本文介绍了使用 scala mongo 驱动程序序列化为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来斯卡拉蒙戈司机和想了解如何映射从文档类?似乎没有任何文档显示这是如何完成的.在 .net 驱动程序中,它就像传递泛型和自动映射字段一样简单.scala 中没有类似的吗?

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?

推荐答案

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

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

这篇关于使用 scala mongo 驱动程序序列化为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆