如何将 JSON 字符串转换为 BSONDocument

How to convert JSON String to a BSONDocument

我有以下使用 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?

更新二:

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.apply(PlayReload.scala:49) ~[na:na]
        at play.sbt.run.PlayReload$$anonfun$taskFailureHandler.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.apply(PlayReload.scala:17) ~[na:na]
        at play.sbt.run.PlayReload$$anonfun$compile.apply(PlayReload.scala:17) ~[na:na]

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

如果你想通过游戏json从String制作一个BSONDocument,你可以使用

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._

Instead of using the default Collection implementation (which interacts with BSON structures + BSONReader/BSONWriter), we use a specialized implementation that works with JsObject + Reads/Writes.

所以你像这样创建专门的集合(必须是 def,而不是 val):

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

从现在开始,您可以将它与播放 json 一起使用,而不是 BSON,因此只需将 Json.parse(jsonString) 作为要插入的文档传入即可。您可以在 link.

中查看更多示例

编辑 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]

ReactiveMongo release note 注释:

When using the support for Play JSON, if the previous error occurs, it necessary to make sure import reactivemongo.play.json._ is used, to import default BSON/JSON conversions.