Version 2, last updated by eltimn at May 05, 2011 15:23 UTC
JObjectParser and CustomSerializers
JObjectParser is used to convert JObjects to DBObjects and vice versa. You normally won’t use this directly, but it is the basis for MongoDocument, JsonObjectField, and MongoJsonObjectListField. If you use any of those you should be aware of some things.
All standard JSON types that lift-json supports are supported directly. BSON types that are not directly supported must use a CustomSerializer. These must be passed to JObjectParser if you are using any of these types. MongoDocument and MongoRecord each have a formats def that is used and can be overridden.
To use JObjectParser directly, it would look something like this;
import net.liftweb._
import json._
import JsonDSL._
import mongodb._
import org.bson.types.ObjectId
import com.mongodb.BasicDBObject
implicit val formats = DefaultFormats + new ObjectIdSerializer
val id = ObjectId.get
val json: JObject = ("_id" -> ("$oid" -> id.toString))
val dbo = JObjectParser.parse(json)
val dbo2 = new BasicDBObject("_id", id)
val json2 = JObjectParser.serialize(dbo2)
assert(dbo == dbo2)
assert(json == json2)
To see all of the CustomSerializers, see Serializers.scala
Note: All String fields are currently checked to see if it is a valid ObjectId. If it is, then an actual ObjectId is created in the DBObject. It is recommended that you use the CustomSerializer instead of relying on this behavior, it may be removed in a future version.