2014-11-25 50 views
0

我正在使用scalatra並將我的servlet配置爲始終返回JSON(如相應指南中所述)。使用MongoDB和Salat使我可以將MongoDBObject讀入我的case類,這似乎很好。ObjectId未序列化爲JSON

我的情況下類:

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

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

打印的情況下類對象輸出這樣的:

Player(547489ee93f4272e548ded63,Peter,...) 

正如你所看到的,OBJECTID是org.bson.types.ObjectId。 的自然而然序列化JSON其發送到瀏覽器:

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

哪裏是我的對象ID?我究竟做錯了什麼?

回答

4

我在網上找到了以下內容: https://gist.github.com/dozed/5631680

小試後,它好像所有我需要做的就是從

protected implicit val jsonFormats: Formats = DefaultFormats 

改變我的servlet代碼

protected implicit val jsonFormats: Formats = DefaultFormats + new ObjectIdSerializer 

並添加

import org.json4s.mongo.ObjectIdSerializer 

也許這會幫助另一個Scalatra-NOOB ... ;-)