如何将JSON字符串转换为BSONDocument [英] How to convert JSON String to a BSONDocument

查看:863
本文介绍了如何将JSON字符串转换为BSONDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下使用reactmongogo驱动程序的功能,并且实际上在写数据库方面做得很好.

I have the following function that uses the reactivemongo driver and actually does a good job writing to the database.

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字符串传递给函数?

But the limitation of that function is that the JSON is hardcoded into a BSONDocument. How can I change it so that I can pass any JSON String into the function?

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

Question in short: How do I convert a JSON String into a 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上),我仍然收到以下错误

The problem now is that import reactivemongo.play.json._ is treated as an unused import (on my IntelliJ) and I still get the following error

[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]

推荐答案

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

First, you could serialize your model classes as BSON using reactivemongo. Check docs to see how.

如果您想通过play json在String中制作BSONDocument,则可以使用

If you want to make a BSONDocument from String through play json you can use

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

修改

我在这里的文档中发现了更多信息:

I found more in the docs here:

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 +读/写一起使用的实现.

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

So you create specialized collection like this (must be def, not val):

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

,从现在开始,您可以将其与play json一起使用,而不是与BSON一起使用,因此只需将Json.parse(jsonString)作为要插入的文档传递就可以了.您可以在链接中看到更多示例.

and from now on you can use it with play json, instead of BSON, so simply passing in Json.parse(jsonString) as a document to insert should work. You can see more examples in the link.

编辑2 我让您的代码可以编译:

Edit 2 I got your code to compile:

程序包控制器

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

and you need JsObject, not just any JsValue

val document = Json.parse(jsonString).as[JsObject]

这篇关于如何将JSON字符串转换为BSONDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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