ObjectId is not serialized to JSON

725 views Asked by At

I am using scalatra and configured my servlet to always return JSON (as described in the respective guide). Using the MongoDB and Salat leads me to the point where I read a MongoDBObject back into my case class - which seems to work great.

My case class:

import org.bson.types.ObjectId
import com.novus.salat.annotations.raw.Key

case class Player(_id: ObjectId, firstName: String, ...)

Printing the case class object outputs this:

Player(547489ee93f4272e548ded63,Peter,...)

As you can see, the objectid is a org.bson.types.ObjectId. The automatical serialization to JSON sends this to the browser:

{"_id":{},"firstName":"Peter",...}

Where is my ObjectID? What am I doing wrong?

1

There are 1 answers

0
eventhorizon On BEST ANSWER

I found the following on the web: https://gist.github.com/dozed/5631680

After a small test it seems as if all I had to do was changing the code in my servlet from

protected implicit val jsonFormats: Formats = DefaultFormats

to

protected implicit val jsonFormats: Formats = DefaultFormats + new ObjectIdSerializer

and add

import org.json4s.mongo.ObjectIdSerializer

Maybe this will help another Scalatra-NOOB... ;-)