Skip to content

Instantly share code, notes, and snippets.

@manuelbernhardt
Created September 2, 2011 14:23
Show Gist options
  • Save manuelbernhardt/1188722 to your computer and use it in GitHub Desktop.
Save manuelbernhardt/1188722 to your computer and use it in GitHub Desktop.
object CHJson extends com.codahale.jerkson.Json {
// this is where we setup out Jackson module for custom de/serialization
val module: SimpleModule = new SimpleModule("delving", Version.unknownVersion())
module.addSerializer(classOf[ObjectId], new ObjectIdSerializer)
module.addDeserializer(classOf[ObjectId], new ObjectIdDeserializer)
mapper.registerModule(module)
}
package extensions
import org.bson.types.ObjectId
import org.codehaus.jackson.{JsonToken, JsonParser, JsonGenerator}
import org.codehaus.jackson.map._
import annotate.JsonCachable
/**
*
* @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
*/
@JsonCachable
class ObjectIdSerializer extends JsonSerializer[ObjectId] {
def serialize(id: ObjectId, json: JsonGenerator, provider: SerializerProvider) {
json.writeString(id.toString)
}
}
class ObjectIdDeserializer extends JsonDeserializer[ObjectId] {
def deserialize(jp: JsonParser, context: DeserializationContext) = {
if (!ObjectId.isValid(jp.getText)) throw context.mappingException("invalid ObjectId " + jp.getText)
new ObjectId(jp.getText)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment