我有以下使用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]
答案 0 :(得分:3)
首先,您可以使用reactivemongo将模型类序列化为BSON。检查文档以了解具体方法。
如果您想通过播放json从BSONDocument
制作String
,可以使用
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 + Reads / Writes一起使用的实现。
所以你创建这样的专门集合(必须是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]
答案 1 :(得分:0)
ReactiveMongo release note说明:
使用Play JSON支持时,如果发生上一个错误,则为 必须确保使用importmongo.play.json._导入 导入默认的BSON / JSON转换。