如何将MongoDBObject转换为JsonString

时间:2013-12-19 13:36:55

标签: mongodb scala lift specs2 casbah

我的mongoDb集合如下所示:

> db.FakeCollection.find().pretty()
{
    "_id" : ObjectId("52b2d71c5c197846fd3a2737"),
    "categories" : [
            {
                    "categoryname" : "entertainment",
                    "categoryId" : "d3ffca550ae44904aedf77cdcbd31d7a",
                    "displayname" : "Entertainment",
                    "subcategories" : [
                            {
                                    "subcategoryname" : "games",
                                    "subcategoryId" : "ff3d0cbeb0eb4960b11b47d7fc64991b",
                                    "displayname" : "Games"
                            }
                    ]
            }
    ]
   }

我想使用带有MongodbCasbah的scala中的Specs2 JsonMatchers为下面的集合编写一个测试用例。 如何将DBObjects转换为字符串?

2 个答案:

答案 0 :(得分:2)

我相信你的方法在这里有点不对。您的收藏应如下所示:

class Category extends BsonRecord[Category] {
  def meta = Category
  object categoryname extends StringField(this, 200)
  object categoryId extends StringField(this, 64)
  object displayname extends StringField(this, 100)
  object subcategories extends BsonRecordListField(this, Category)
}
object Category extends Category with BsonMetaRecord[Category] {
}

class FakeCollection extends MongoRecord[FakeCollection] with ObjectIdPk[FakeCollection] {
  def meta = FakeCollection
  object categories extends BsonRecordListField(this, Category)
}
object FakeCollection extends FakeCollection with MongoMetaRecord[FakeCollection] {
  override def collectionName = "fakecollection"
  def getEntryByName: List[Category] = {
    FakeCollection.find
  }
}

使用该方法,您可以:

import net.liftweb.json.JsonAST.JValue;
import net.liftweb.http.js.JsExp;
import net.liftweb.http.js.JsExp._;
import net.liftweb.json.JsonDSL.seq2jvalue
val json: JsExp = seq2JValue(FakeColleciton.find.map(_.asJValue))
val stringContent = json.toJsCmd; // now it's here, you can match.

看看HERE,了解如何添加Foursquare Rogue让您的生活更轻松。

答案 1 :(得分:1)

简短回答:

val doc: com.mongodb.DBObject = ???
pretty(render(net.liftweb.mongodb.JObjectParser.serialize(doc)))

很长的答案解释了发生了什么。为清晰起见,我提供了完整的类型名称:

import net.liftweb.mongodb.JObjectParser
import net.liftweb.json.DefaultFormats

// default JSON formats for `parse` and `serialize` below
implicit val formats = DefaultFormats

// Convert DBObject to JValue:
val doc: com.mongodb.DBObject = ??? // get it somehow
val jsonDoc: net.liftweb.json.JValue = JObjectParser.serialize(doc)

// Convert JValue to DBObject:
val doc2: net.liftweb.json.JObject = ???
val dbObj: com.mongodb.DBObject = JObjectParser.parse(doc2)

// Render JSON as String:
import net.liftweb.json._
pretty(render(jsonDoc))
// or use compactRender, compact(render(jsonDoc)), etc

要比较JSON文档,有Diff:val Diff(changed, added, deleted) = json1 diff json2

此处有更多信息:https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/

您可以使用specs2和Lift Diff进行测试,例如:

json1 diff json2 mustEqual Diff(changedJson, addedJson, JNothing)