简体   繁体   中英

ObjectId is not serialized to JSON

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?

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... ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM