Search code examples
mongodbscalaliftspecs2casbah

How to Convert MongoDBObject to JsonString


My mongoDb collection looks like this:

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

I want to write a test case for the below collection using Specs2 JsonMatchers in scala with MongodbCasbah. How do I convert DBObjects to Strings?


Solution

  • Short answer:

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

    Long answer that explains what's going on. I included full type names for clarity:

    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
    

    To compare JSON docs there is Diff: val Diff(changed, added, deleted) = json1 diff json2.

    More info here: https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/.

    You can test with specs2 and Lift Diff this way for example:

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