我正在使用 scalatra 并将我的 servlet 配置为始终返回 JSON(如相应指南中所述)。使用 MongoDB 和 Salat 使我将 MongoDBObject 读回到我的案例类中 - 这似乎工作得很好。
我的案例类别:
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",...}
我的 ObjectID 在哪里?我做错了什么?
最佳答案
我在网上找到了以下内容: https://gist.github.com/dozed/5631680
经过一次小测试后,似乎我所要做的就是将 servlet 中的代码更改为
protected implicit val jsonFormats: Formats = DefaultFormats
至
protected implicit val jsonFormats: Formats = DefaultFormats + new ObjectIdSerializer
并添加
import org.json4s.mongo.ObjectIdSerializer
也许这会帮助另一个 Scalatra-NOOB...;-)
关于json - ObjectId 未序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27128766/