代码之家  ›  专栏  ›  技术社区  ›  summerNight

如何将JSON字符串转换为BSONDocument

  •  1
  • summerNight  · 技术社区  · 10 年前

    我有下面的函数,它使用了reactivemongo驱动程序,实际上很好地写入了数据库。

    def writeDocument() = {
        val document = BSONDocument(
          "firstName" -> "Stephane",
          "lastName" -> "Godbillon",
          "age" -> 29)
    
        val future = collection.insert(document)
    
        future.onComplete {
          case Failure(e) => throw e
          case Success(result) => {
            println("successfully inserted document with result = " + result)
          }
        }
      }
    

    但该函数的限制是JSON被硬编码到BSONDocument中。如何更改它,以便可以将任何JSON字符串传递到函数中?

    简言之:如何将JSON字符串转换为BSONDocument?

    更新2:

    package controllers
    
    //import play.api.libs.json._
    //import reactivemongo.bson._
    //import play.api.libs.json.Json
    
    import scala.util.{Success, Failure}
    import reactivemongo.api._
    //import scala.concurrent.ExecutionContext.Implicits.global
    
    
    import play.modules.reactivemongo.json.collection._
    import reactivemongo.play.json._
    
    object Mongo {
    
      //val collection = connect()
    
      def collection: JSONCollection = {
        val driver = new MongoDriver
        val connection = driver.connection(List("localhost"))
        val db = connection("superman")
        db.collection[JSONCollection]("IncomingRequests")
      }
    
    
      // TODO: Make this work with any JSON String
      def writeDocument() = {
    
        val jsonString = """{
                           | "guid": "alkshdlkasjd-ioqweuoiquew-123132",
                           | "title": "Hello-2016",
                           | "year": 2016,
                           | "action": "POST",
                           | "start": "2016-12-20",
                           | "stop": "2016-12-30"}"""
    
    
        val document = Json.parse(jsonString)
        val future = collection.insert(document)
        future.onComplete {
          case Failure(e) => throw e
          case Success(result) => {
            println("successfully inserted document with result = " + result)
          }
        }
      }
    
    }
    

    现在的问题是 import reactivemongo.play.json._ 被视为未使用的导入(在我的IntelliJ上),我仍然收到以下错误

    [info] Compiling 9 Scala sources and 1 Java source to /Users/superman/target/scala-2.11/classes...
    [error] /Users/superman/app/controllers/Mongo.scala:89: No Json serializer as JsObject found for type play.api.libs.json.JsValue. Try to implement an implicit OWrites or OFormat for this type.
    [error] Error occurred in an application involving default arguments.
    [error]     val future = collection.insert(document)
    [error]                                   ^
    [error] one error found
    [error] (compile:compileIncremental) Compilation failed
    [error] application - 
    
    ! @6oo00g47n - Internal server error, for (POST) [/validateJson] ->
    
    play.sbt.PlayExceptions$CompilationException: Compilation error[No Json serializer as JsObject found for type play.api.libs.json.JsValue. Try to implement an implicit OWrites or OFormat for this type.
    Error occurred in an application involving default arguments.]
            at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27) ~[na:na]
            at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27) ~[na:na]
            at scala.Option.map(Option.scala:145) ~[scala-library-2.11.6.jar:na]
            at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:49) ~[na:na]
            at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:44) ~[na:na]
            at scala.Option.map(Option.scala:145) ~[scala-library-2.11.6.jar:na]
            at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:44) ~[na:na]
            at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:40) ~[na:na]
            at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17) ~[na:na]
            at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17) ~[na:na]
    
    2 回复  |  直到 10 年前
        1
  •  3
  •   Łukasz    10 年前

    首先,可以使用reactivemongo将模型类序列化为BSON。查看文档以了解如何操作。

    如果你想 BSONDocument 从…起 String 通过play json,您可以使用

    val playJson: JsValue = Json.parse(jsonString)
    val bson: BSONDocument = play.modules.reactivemongo.json.BSONFormats.reads(playJson).get
    

    编辑

    我在这里的文档中找到了更多:

    http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html

    你可以导入这两个

    import reactivemongo.play.json._
    import play.modules.reactivemongo.json.collection._
    

    而不是使用默认的Collection实现(它与 BSON结构+BSONReader/BSONWriter),我们使用 与JsObject+读/写一起工作的实现。

    所以您可以创建这样的专门集合(必须是 def 不 val ):

    def collection: JSONCollection = db.collection[JSONCollection]("persons")
    

    从现在起,您可以将其用于play-json,而不是BSON,所以只需传入 Json.parse(jsonString) 作为要插入的文档应该有效。您可以在链接中看到更多示例。

    编辑2 我得到了要编译的代码:

    组件控制器

    import play.api.libs.concurrent.Execution.Implicits._
    import play.api.libs.json._
    import play.modules.reactivemongo.json.collection.{JSONCollection, _}
    import reactivemongo.api.MongoDriver
    import reactivemongo.play.json._
    import play.api.libs.json.Reads._
    
    import scala.util.{Failure, Success}
    
    
    object Mongo {
    
      def collection: JSONCollection = {
        val driver = new MongoDriver
        val connection = driver.connection(List("localhost"))
        val db = connection("superman")
        db.collection[JSONCollection]("IncomingRequests")
      }
    
      def writeDocument() = {
    
       val jsonString = """{
                           | "guid": "alkshdlkasjd-ioqweuoiquew-123132",
                           | "title": "Hello-2016",
                           | "year": 2016,
                           | "action": "POST",
                           | "start": "2016-12-20",
                           | "stop": "2016-12-30"}"""
    
    
        val document = Json.parse(jsonString).as[JsObject]
        val future = collection.insert(document)
        future.onComplete {
          case Failure(e) => throw e
          case Success(result) =>
            println("successfully inserted document with result = " + result)
        }
      }
    }
    

    重要的是

    import play.api.libs.json.Reads._
    

    你需要 JsObject ,不只是任何 JsValue

    val document = Json.parse(jsonString).as[JsObject]
    
        2
  •  0
  •   lucas    10 年前

    反应式蒙哥 release note 笔记:

    当使用对Play JSON的支持时,如果出现之前的错误 必须确保导入reactivemongo.play.json用于 导入默认BSON/JSON转换。

    推荐文章